使用TextToSpeech实现文本转音频(自动朗读)

主要方法

setLanguage:设置语言的类型

speak:传入文本播放声音

synthesizeToFile:传入文本保存为音频

shutdown:释放TextToSpeech资源

package prictise.lxm.prictise;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Locale;

/**
 * 使用TextToSpeech实现自动朗读
 */
public class MainActivity extends Activity{

    TextToSpeech textToSpeech;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //获取界面视图
        final EditText edTxtSpeak = (EditText)findViewById(R.id.edTxt_speak);
        final Button btnSpeak = (Button)findViewById(R.id.btn_speak);
        final Button btnSave = (Button)findViewById(R.id.btn_save);

        textToSpeech = new TextToSpeech(this,new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                //初始化成功,设置语言
                if(status == TextToSpeech.SUCCESS){
                    //设置语言为美式英语
                    int result = textToSpeech.setLanguage(Locale.US);
                    //设置语言为中文
                   // int result = textToSpeech.setLanguage(Locale.CHINA);
                    if(result != TextToSpeech.LANG_AVAILABLE &&
                            result != TextToSpeech.LANG_COUNTRY_AVAILABLE){ //不支持当前语言
                        Toast.makeText(MainActivity.this,"不支持" + textToSpeech.getLanguage().
                                getDisplayName(),Toast.LENGTH_SHORT).show();
                        //设置发音按钮不可用
                        btnSave.setEnabled(false);
                        btnSpeak.setEnabled(false);
                    }
                }
            }
        });

        //播放按钮
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textToSpeech.speak(edTxtSpeak.getText().toString(),TextToSpeech.QUEUE_ADD,null);
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textToSpeech.synthesizeToFile(edTxtSpeak.getText().toString(),null,"speakUs");
            }
        });
    }

    protected void onDestroy() {
        //释放tts
        if(textToSpeech != null) {
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }


}






  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值