Android中使用TTS(TextToSpeech)将文字转为语音

实现步骤:

  1. 创建TextToSpeech对象,创建时传入OnInitListener监听器
  2. 设置TextToSpeech所使用的语言、国家选项
  3. 调用speak()或synthesizeToFile方法
  4. 关闭TTS,回收资源

  • 在布局中加入EditText用于获取文字,加入Button用于控制播放或存储合成的声音文件
  • 代码:
    • 初始化
TextToSpeech textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.US);
                    if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
                        Toast.makeText(MainActivity.this, "暂不支持该语言", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
  • 播放或存储为文件
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onClick(View view) {
                textToSpeech.setSpeechRate(1);
                textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null, "speech");
                Snackbar.make(view, "是否存储该声音文件", Snackbar.LENGTH_LONG)
                        .setAction("存储", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                textToSpeech.synthesizeToFile(editText.getText().toString(), null, new File("/mnt/sdcard/sound.mp3"), "record");
                                Toast.makeText(MainActivity.this, "存储成功", Toast.LENGTH_SHORT).show();
                            }
                        }).show();
            }
        });
  • 回收资源
protected void onDestroy() {
        super.onDestroy();
        if (textToSpeech != null) {
            textToSpeech.shutdown();
        }
    }

你可能感兴趣的:(Android)