对话中的文本到语音,奇怪的行为

时间:2015-07-06 11:15:16

标签: android

代码打开一个对话框,用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();
}

显然,对话框中有两个按钮,setPositiveButtonsetnegativeButton,正面按钮将输出保存为.wav文件,同时播放输出。 否定按钮也会播放输出。但 t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null); 在正按钮中不产生任何输出。是什么造成的?使用Dialogs时要注意什么?

1 个答案:

答案 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();

因此,在你告诉它开始之后你会做更多的事情,然后告诉它停止 - 很可能在任何声音产生之前。