Android 使用TextToSpeech - 在线文本转语音

工具类


/**
 * date:2023/8/17
 * author:wangsimin
 * funcation:语音播报工具类
 */
public class TextToSpeechUtils {
    public static final String TAG = "TextToSpeechUtils";
    private static TextToSpeechUtils textToSpeechUtils;
    private TextToSpeech mTextToSpeech;    // TTS对象

    public static TextToSpeechUtils getInstance() {
        if (textToSpeechUtils == null) {
            textToSpeechUtils = new TextToSpeechUtils();
        }
        return textToSpeechUtils;
    }

    private TextToSpeechUtils() {
    }

    public void initTextToSpeech(Context context) {
        mTextToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = mTextToSpeech.setLanguage(Locale.CHINA);
                    // TextToSpeech.LANG_MISSING_DATA:表示语言的数据丢失
                    // TextToSpeech.LANG_NOT_SUPPORTED:不支持
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        ToastUtils.show("不支持语音播报");
                    }
                } else {
                    Log.e(TAG, "初始化失败");
                }
            }
        });
        // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
        mTextToSpeech.setPitch(0.8f);
        // 设置语速
        mTextToSpeech.setSpeechRate(1.0f);
    }

    public void close() {
        if (mTextToSpeech != null) {
            mTextToSpeech.stop();        // 不管是否正在朗读TTS都被打断
            mTextToSpeech.shutdown();    // 关闭,释放资源
            mTextToSpeech = null;
        }
    }

    /**
     * 开始播报
     * @param speakStr 播报内容
     */
    public void speak(String speakStr) {
        try {
            if (mTextToSpeech != null && !mTextToSpeech.isSpeaking()) {
                mTextToSpeech.speak(speakStr, TextToSpeech.QUEUE_ADD, null, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

初始化

//文字转语音初始化
TextToSpeechUtils  speechUtils = TextToSpeechUtils.getInstance();
speechUtils.initTextToSpeech(this);

播报内容

speechUtils.speak("哈哈哈哈");

释放资源

 @Override
    public void onDestroy() {
        try {
            if (speechUtils != null) {
                speechUtils.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值