为防止应用程序在语音转文字和文字转语音过程中自我监听,可以使用以下方法:
示例代码:
SpeechRecognizer sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new RecognitionListener() { @Override public void onResults(Bundle results) { //处理识别结果 sr.stopListening(); //停止监听 } });
sr.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
示例代码:
TextToSpeech tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if(status == TextToSpeech.SUCCESS) { tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() { @Override public void onUtteranceCompleted(String utteranceId) { tts.stop(); //停止语音引擎 } }); tts.speak("要转换成语音的文本", TextToSpeech.QUEUE_FLUSH, null, "utteranceId"); } } });
注意:需要在Activity的onDestroy方法中释放SpeechRecognizer和TextToSpeech对象:
@Override protected void onDestroy() { super.onDestroy(); if(sr != null) { sr.destroy(); } if(tts != null) { tts.shutdown(); } }