自学内容网 自学内容网

android 7.0 tts文字转语音

支持中文的SDK 语音引擎下载


import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;

public class SystemTTS {
    private static final String TAG = "SystemTTS";
    private static SystemTTS instance;
    private TextToSpeech textToSpeech;
    private boolean isSupport = true;

    private SystemTTS(Context context) {
        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.CHINA);
                    textToSpeech.setPitch(1.0f); // 设置音调
                    textToSpeech.setSpeechRate(1.0f); // 设置语速
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        isSupport = false;
                        Log.i(TAG, "系统不支持中文语音播报");
                    }
                }else {
                    Log.e(TAG, "初始化系统TTS 失败");
                }
            }
        });
    }

    public static SystemTTS getInstance(Context context) {
        if (instance == null) {
            instance = new SystemTTS(context);
        }
        return instance;
    }

    public void speak(String text) {
        if (!isSupport) {
            return;
        }
        if (textToSpeech != null) {
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
    }

    public void destroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        instance = null;
    }
SystemTTS.getInstance(this).speak("测试语音输出");

原文地址:https://blog.csdn.net/qq_32698323/article/details/140230198

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!