语音朗读

语音朗读:Text-to-Speech

  • 首先确认是否安装了语音包
Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(intent, TTS_DATA_CHECK);

如果安装了语言包那么返回的将是Engine.CHECK_VOICE_DATA_PASS

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK) {
if (resultCode == Engine.CHECK_VOICE_DATA_PASS) {
//表示已经安装了语言包
}
super.onActivityResult(requestCode, resultCode, data);
}
}
  • 创建并初始化TTS
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TTS_DATA_CHECK) {
if (resultCode == Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(MainActivity.this, new OnInitListener() {
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
ttsInit = true;
if (tts.isLanguageAvailable(Locale.UK) > 0) {
tts.setLanguage(Locale.UK);
tts.setPitch(0.8f);
tts.setSpeechRate(1.1f);
}
} else {
Intent intent = new Intent(
Engine.ACTION_INSTALL_TTS_DATA);
startActivity(intent);
}
}
});
}
}
super.onActivityResult(requestCode, resultCode, data);
}
  • 使用TTS朗读
public void onClick(View v) {
String str = mTextToSpeechEt.getText().toString().trim();
switch (v.getId()) {
case R.id.readBtn:
if (!TextUtils.isEmpty(str)) {
if (tts != null && ttsInit) {
tts.speak(str, TextToSpeech.QUEUE_ADD, null);
}
}
break;
default:
break;
}
}
  • 在销毁的时候关闭TTS资源
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}

语音识别

应用程序中接收输入语音
/*允许在应用程序中接收输入语音*/
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
/*指定用于分析输入音频的语言模型*/
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
/*指定返回潜在识别的结果*/
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.CHINA);
/*提示用户讲话*/
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "请讲话");
startActivityForResult(intent, RECOGNIZE);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==RECOGNIZE){
if(resultCode==RESULT_OK){
ArrayList<String> result = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
float [] configence =
data.getFloatArrayExtra(
RecognizerIntent.EXTRA_CONFIDENCE_SCORES);
StringBuffer sb = new StringBuffer();
for(int i=0;i<result.size();i++){
sb.append(result.get(i)+": "+configence[i]+'\n');
}
mResultTV.setText(sb.toString());
}}
super.onActivityResult(requestCode, resultCode, data);
}
启动网络搜索
Intent webIntent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
webIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
startActivityForResult(webIntent, 0);
Contents
  1. 1. 语音朗读
  2. 2. 语音识别
    1. 2.1. 应用程序中接收输入语音
    2. 2.2. 启动网络搜索