点击安卓按钮实现文字播报

安卓将文字转换成语音

先实例化 " TextToSpeech”
onInit() 函数 检查当前的是否有TTS服务。

textToSpeech = new TextToSpeech(this.activity.getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                Log.i(TAG,"onInit");
                if(status == TextToSpeech.SUCCESS){
                    int result =  textToSpeech.setLanguage(Locale.CHINA);
                    if(result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED
                    ){
                        Log.i(TAG,"数据丢失或者不支持");
                    }
                }
            }
        });

完整代码:


import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import org.w3c.dom.Text;

import java.util.Locale;

import wendu.dsbridge.DWebView;

public class SpeechService{
    private static final String TAG  = "SpeechService";

    DWebView webView;
    Activity activity;
    TextToSpeech textToSpeech;

    private static SpeechService speechService = new SpeechService();

    private SpeechService(){}

    public static SpeechService getInstance(){
        return speechService;
    }

    /**
     *  先初始化服务
     * @param webView
     * @param activity
     */
    public void initService(DWebView webView, Activity activity){
        this.webView = webView;
        this.activity = activity;

        textToSpeech = new TextToSpeech(this.activity.getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                Log.i(TAG,"onInit");
                if(status == TextToSpeech.SUCCESS){
                    int result =  textToSpeech.setLanguage(Locale.CHINA);
                    if(result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED
                    ){
                        Log.i(TAG,"数据丢失或者不支持");
                    }
                }
            }
        });
    }


    public void onDestroy() {
        // 不管是否正在朗读TTS都被打断
        textToSpeech.stop();
        // 关闭,释放资源
        textToSpeech.shutdown();
    }



    /**
     *  发音
     * @param content
     */
    public void speak(String content){
        Log.i(TAG,"语音+"+content);
        if(textToSpeech != null){
            if(textToSpeech.isSpeaking()){
                textToSpeech.stop();
            }
            Log.i(TAG,"语音2"+content);
            // 设置语音的音速,音高
            textToSpeech.setPitch(0.5f);
            textToSpeech.setSpeechRate(1f);
            textToSpeech.speak(content, TextToSpeech.QUEUE_FLUSH, null);
        }
    }
}

必须有TTS语音引擎。 可以使用的谷歌的文本转换语音引擎。(从应用商店下载apk)