import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioManager;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.util.HashMap;
import java.util.Locale;
import java.util.Random;
public class MyTTS implements TextToSpeech.OnInitListener, TextToSpeech.OnUtteranceCompletedListener {
private TextToSpeech mTTS;
private Context mContext;
private String text;
/**
* 初始化
*
* @param status
*/
@Override
public void onInit(int status) {
//判断是否转化成功
if (status == TextToSpeech.SUCCESS) {
//初始化时注册监听器
mTTS.setOnUtteranceCompletedListener(this);
//设置语言为中文
int languageCode = mTTS.setLanguage(Locale.CHINESE);
//判断是否支持这种语言,Android原生不支持中文,使用科大讯飞的tts引擎就可以了
if (languageCode == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.d("TAG", "onInit: 不支持这种语言");
} else {
//不支持就改成英文
mTTS.setLanguage(Locale.US);
}
//设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
mTTS.setPitch(1.0f);
//设置语速
mTTS.setSpeechRate(1.0f);
//在onInIt方法里直接调用tts的播报功能
mTTS.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
@Override
public void onUtteranceCompleted(String s) {
Log.i("MYTTS", s);
//语音成功播放完毕之后,可以do something
}
public MyTTS(Context mContext) {
this.mContext = mContext;
//监听器就直接传入本类
this.mTTS = new TextToSpeech(mContext, this);
}
public MyTTS(Context mContext, String str) {
this.mContext = mContext;
this.text = str;
//监听器就直接传入本类
this.mTTS = new TextToSpeech(mContext, this);
}
/**
* 播报方法,需要传入播报的内容
*
* @param text 播报的内容
*/
public void mySpeak(String text,String s ) {
if(text != null) {
HashMap myHashAlarm = new HashMap();
myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, s); //utteranceId == "SOME MESSAGE"
mTTS.setPitch(1.0f);
//设置语速
mTTS.setSpeechRate(1.0f);
mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, myHashAlarm);
}
}
/**
* 销毁播报方法,直接调用
*/
public void stopTTS() {
mTTS.stop();
mTTS.shutdown();
mTTS = null;
}
}