Text To Speech即TTS技术
原生Android系统自带了一个Pico TTS引擎,但不支持中文;市面上离线的文字转语音,某讯,某度都是收费的,并且还设计到版权的问题, 实际上谷歌内置TextToSpeach类帮助开发者实现这一功能, 市场上的手机很多已经内置了文字转语音的引擎, 如果没有则安装一个apk即可,切换一下, 如下图所示:

点击Google文字转语音引擎设置, 下载中文的安装包; 即可以在代码中进行语音播报,
package hz.hzhztech.publiclibrary.utils;
import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.support.annotation.RequiresApi;
import com.blankj.utilcode.util.ToastUtils;
import java.util.Locale;
import hz.hzhztech.publiclibrary.application.App;
public class TtsManager {
private TtsManager() {
}
private static class SingletonHoler {
public static final TtsManager INSTANCE = new TtsManager();
}
public static TtsManager getInstance() {
return SingletonHoler.INSTANCE;
}
private TextToSpeech mSpeech;
private boolean mIsInited;
// private UtteranceProgressListener mSpeedListener;
public void init() {
destory();
mSpeech = new TextToSpeech(App.getInstance(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mSpeech.setLanguage(Locale.CHINESE);
// mSpeech.setPitch(1.0f); // 设置音调
// mSpeech.setSpeechRate(1.5f); // 设置语速
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
//语音合成初始化失败,不支持语种
mIsInited = false;
ToastUtils.showLong("语音不可用,请确认是否安装语音引擎");
} else {
mIsInited = true;
}
// mSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
// @Override
// public void onStart(String utteranceId) {
// //======语音合成 Start
// if (mSpeedListener != null)
// mSpeedListener.onStart(utteranceId);
// }
//
// @Override
// public void onDone(String utteranceId) {
// //======语音合成 Done
// if (mSpeedListener != null)
// mSpeedListener.onDone(utteranceId);
// }
//
// @Override
// public void onError(String utteranceId) {
// //======语音合成 Error
// if (mSpeedListener != null)
// mSpeedListener.onError(utteranceId);
// }
// });
}
}
});
}
// public void setSpeechListener(UtteranceProgressListener listener) {
// this.mSpeedListener = listener;
// }
public boolean speakText(String text) {
if (!mIsInited) {
//语音合成失败,未初始化成功
init();
return false;
}
if (mSpeech != null) {
int result = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
result = mSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, "");
}
return result == TextToSpeech.SUCCESS;
}
return false;
}
public void stop() {
if (mSpeech != null && mSpeech.isSpeaking()) {
mSpeech.stop();
}
}
public boolean isSpeaking() {
if (mSpeech == null)
return false;
return mSpeech.isSpeaking();
}
public void destory() {
if (mSpeech != null) {
mSpeech.stop();
mSpeech.shutdown();
}
}
}
本文介绍如何在Android应用中使用Google内置的TextToSpeech类实现中文语音合成,包括引擎设置、代码示例及常见问题解决。
1807

被折叠的 条评论
为什么被折叠?



