代码打开一个对话框,用EditText
将用户输入的TTS
转换为语音并播放输出。
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("SAVE", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File directory = new File(Environment.getExternalStorageDirectory()+"/myAppCache/");
//if (!directory.exists()) {
directory.mkdirs();
//}
HashMap<String, String> myHashRender = new HashMap();
String toSpeak = input.getText().toString();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
String destFileName = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, toSpeak);
t1.synthesizeToFile(toSpeak, myHashRender, destFileName);
t1.stop();
t1.shutdown();
}
});
builder.setNegativeButton("Play", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String toSpeak = input.getText().toString();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
builder.show();
}
显然,对话框中有两个按钮,setPositiveButton
和setnegativeButton
,正面按钮将输出保存为.wav
文件,同时播放输出。
否定按钮也会播放输出。但
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
在正按钮中不产生任何输出。是什么造成的?使用Dialogs时要注意什么?
答案 0 :(得分:1)
这与Dialogs无关,问题是你要告诉它停止!
对speak()
的调用是非阻止的。来自API:
此方法返回时,合成可能尚未完成(甚至已启动!)。
您的代码是:
START SPEAKING -> t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
String destFileName = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, toSpeak);
t1.synthesizeToFile(toSpeak, myHashRender, destFileName);
STOP SPEAKING -> t1.stop();
因此,在你告诉它开始之后你会做更多的事情,然后告诉它停止 - 很可能在任何声音产生之前。