我有一个片段,可以播放文件中的文本到语音。在播放时,我想通过按设备上的“后退”按钮来停止TTS。目前,只有在TTS完成后,它才会响应后退键。我已经尝试了很多事情,但是找不到解决方案。简而言之,我的代码是:
mTts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status == TextToSpeech.SUCCESS){
int result=mTts.setLanguage(Locale.UK);
if(result==TextToSpeech.LANG_MISSING_DATA ||
result==TextToSpeech.LANG_NOT_SUPPORTED){
showLog("This Language is not supported");
}
else{
String filePath="In the beginning God created the heavens and the earth. Now the earth proved to be formless and waste. ";
ttsTextbox.setText(filePath);
mTts.setPitch(ttsPitch);
mTts.setSpeechRate(ttsRate);
//adjust sound level
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//store curr volume
int amCurrVol = am.getStreamVolume(am.STREAM_MUSIC);
int amStreamMusicMaxVol = am.getStreamMaxVolume(am.STREAM_MUSIC);
am.setStreamVolume(am.STREAM_MUSIC, (ttsVolume*amStreamMusicMaxVol)/100, (ttsVolume*amStreamMusicMaxVol)/100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mTts.speak(filePath, TextToSpeech.QUEUE_FLUSH, null, "99");
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"99");
mTts.speak(filePath, TextToSpeech.QUEUE_FLUSH, params);
}
}
}
else
showLog("Initilization Failed!");
}
});
,后退按钮侦听器是:
@Override
public void onBackPressed() {
showLog("----back key pressed");
super.onBackPressed();
if(mTts.isSpeaking()){
showLog("----stopping tts because back key pressed");
stopTTS();
}
return;
}