【问题标题】:Android TextToSpeech does not work if called directly from onCreate如果直接从 onCreate 调用 Android TextToSpeech 不起作用
【发布时间】:2018-04-28 10:44:53
【问题描述】:

这是一个按下按钮时的测试活动,textToSpeech 工作得很好,但是当调用函数 playString() 时它不会工作,playString() 是从这个 TestActivity 的 onCreate() 调用的。

public class TestActivity  extends Activity {
    TextToSpeech textToSpeech;
    EditText editText;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        editText=(EditText)findViewById(R.id.editText);
        button=(Button)findViewById(R.id.button);

        textToSpeech=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.UK);
                }
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sentence = "Testing String";
                textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
            }
        });
        playString();
    }

    public void playString(){
        String sentence = "Testing String";
        textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
    }

    public void onPause(){
        if(textToSpeech !=null){
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onPause();
    }
}

【问题讨论】:

  • 检查下面的答案

标签: android text-to-speech oncreate


【解决方案1】:

来自documentation

TextToSpeech 实例只有在完成初始化后才能用于合成文本。

初始化可能需要很长时间(在我的设备上大约需要 30 秒),因此您不能使用带有随机延迟的处理程序。
相反,您可以将playString() 放在onInit 块中,紧跟在textToSpeech.setLanguage(Locale.UK); 之后,这样字符串就会在可以播放时播放。

【讨论】:

    【解决方案2】:

    请在 oncreate 方法中使用以下代码来调用 texttospeech:

     textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    textToSpeech.setLanguage(Locale.UK);
                }
            }
        });
    
    
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 100ms
    
                String sentence = "Testing String";
                textToSpeech.speak(sentence, TextToSpeech.QUEUE_FLUSH, null);
            }
        }, 500);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多