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();
        }
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值