您的位置:首页 > 移动开发 > Android开发

Android 语音播放(文字TTS)

2022-02-15 16:03 3687 查看

原文地址:Android 语音播放(文字TTS) | Stars-One的杂货小窝

基于Google内置的TTS引擎,封装了个语音播放的工具类

使用

//初始化
SpeechService.init(this);

//在如何地方调用都可以
SpeechService.speakText("这是一段文本的语音测试");

//别忘记释放资源
SpeechService.release();

坑说明

1.Flyme系统不支持

测试发现,如果是魅族手机,Flyme系统已经把TTS引擎删了,所以会出现语音引擎初始化失败的原因,可以试着安装下其他的TTS引擎来进行尝试

2.Android 11无法播放

需要在清单文件假如下面代码

<queries>
<intent>
<action android:name="android.intent.action.TTS_SERVICE" />
</intent>
</queries>

如下图所示

工具类源码

public class SpeechService {
private static TextToSpeech textToSpeech;

/**
* 初始化
* @param activity
* @return
*/
public static void init(Activity activity) {
if (textToSpeech == null) {
//初始化tts语音
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
// 如果装载TTS引擎成功
if (status == TextToSpeech.SUCCESS) {
// 设置使用美式英语朗读
int result = textToSpeech.setLanguage(Locale.CHINA);
// 如果不支持所设置的语言
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
&& result != TextToSpeech.LANG_AVAILABLE) {
ToastUtils.showShort("该tts不支持中文");
}
} else {
textToSpeech = null;
}
}
});
}
}

/**
* 朗读语音
* @param text
*/
public static void speakText(String text) {
if (textToSpeech != null) {
textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null);
} else {
Log.e("test","语音还未初始化");
}
}

/**
* 关闭并释放资源
*/
public static void release() {
if (textToSpeech != null) {
// 不管是否正在朗读TTS都被打断
textToSpeech.stop();
// 关闭,释放资源
textToSpeech.shutdown();
textToSpeech = null;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: