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();
    }

你可能感兴趣的:(android)