Android 原生语音播报

Android系统本身自带的语音引擎不支持中文,所以需要依赖 如 科大讯飞、度秘 等,类似语音引擎才可以。

三步:

1:安装语音引擎。  安装包百度找一下。安装到需要播报的机子上

如果没找到的话,这里有:https://download.csdn.net/download/qq_39731011/15047992        //为了防止你们懒得自己找,特设5C币门槛

2:设置采用该引擎: 设置— 语音和输入法— 文字转语音(TTS)输出— 首选引擎—选择你安装的引擎

3:将以下工具类复制到项目中,一行代码直接用

一行代码调用:

SpeechUtils.getInstance(this).speakText("语音播报的内容");

/**
 * Created by Xinghai.Zhao on 2021/2/4
 * android自带语音识别工具,如果要支持中文需要配合其他语音引擎
 */
import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.text.TextUtils;

import java.util.Locale;

public class SpeechUtils {
    private Context context;


    private static final String TAG = "SpeechUtils";
    private static volatile SpeechUtils singleton;

    private TextToSpeech textToSpeech; // TTS对象
    // private boolean isOld;

    public static SpeechUtils getInstance(Context context) {
        if (singleton == null) {
            synchronized (SpeechUtils.class) {
                if (singleton == null) {
                    singleton = new SpeechUtils(context);
                }
            }
        }
        return singleton;
    }

    public SpeechUtils(Context context) {
        this.context = context;
        speakText(null);
    }


    /**
     * 关闭 语音合成
     */
    public void shutdown(){
        if(textToSpeech!=null){
            textToSpeech.stop();
            textToSpeech.shutdown();
            textToSpeech = null;
        }
    }

    /**
     * 第二个参数queueMode用于指定发音队列模式,两种模式选择
     * (1)TextToSpeech.QUEUE_FLUSH:该模式下在有新任务时候会清除当前语音任务,执行新的语音任务
     * (2)TextToSpeech.QUEUE_ADD:该模式下会把新的语音任务放到语音任务之后,
     * @param text
     */
    public void speakText(String text) {
        if(textToSpeech==null){
            textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
                @Override
                public void onInit(int i) {
                    if (i == TextToSpeech.SUCCESS) {
                        int result = textToSpeech.setLanguage(Locale.CHINA);
                        textToSpeech.setPitch(1.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
                        textToSpeech.setSpeechRate(1.0f);
                    /*if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE
                            && result != TextToSpeech.LANG_AVAILABLE){
                        Toast.makeText(context, "TTS暂时不支持这种语音的朗读!",
                                Toast.LENGTH_LONG).show();
                    }else {
                        textToSpeech.setPitch(1.0f);// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
                        textToSpeech.setSpeechRate(1.0f);
                    }*/
                    }
                }
            });
        }
        if(!TextUtils.isEmpty(text)){
            textToSpeech.speak(text,TextToSpeech.QUEUE_ADD, null);
        }

    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章