TextToSpeech 即文字转语音服务,是Android系统提供的原生接口服务,原生的tts引擎应用通过检测系统语言,用户可以下载对应语言的资源文件,达到播报指定语音的文字的能力。但是一切都是在google service的环境下的,在国内使用的Android设备中谷歌服务都是禁用的,而国内最主要的也是需要中文的文字播报能力,那如何实现呢。
TextToSpeech源码解析
如何查看系统源码,请查看我之前的文章:{
如何查看Android系统源码
https://blog.csdn.net/caizehui/article/details/103823057}
首先,我习惯读一下类注释,这里讲的主要是TextToSpeech可以将文本转语音播放或者生成音频文件,且功能必须在初始化完成之后,而这个初始化接口就是TextToSpeech.OnInitListener,当你使用完成TextToSpeech实例,记得shutdown去释放引擎使用的native资源
/**
*
* Synthesizes speech from text for immediate playback or to create a sound file.
* <p>A TextToSpeech instance can only be used to synthesize text once it has completed its
* initialization. Implement the {@link TextToSpeech.OnInitListener} to be
* notified of the completion of the initialization.<br>
* When you are done using the TextToSpeech instance, call the {@link #shutdown()} method
* to release the native resources used by the TextToSpeech engine.
*/
public class TextToSpeech {
然后我们看下这个初始化回调接口,可以看到onInit的status参数返回Success时表示初始化成功,任何事都是需要在这之后才能去调用,比如设置参数,或者调用播放接口等,否则是不管用的。
这里要学习下谷歌的注释方法,把参数的所有状态也能列出来,很清晰。
/**
* Interface definition of a callback to be invoked indicating the completion of the
* TextToSpeech engine initialization.
*/
public interface OnInitListener {
/**
* Called to signal the completion of the TextToSpeech engine initialization.
*
* @param status {@link TextToSpeech#SUCCESS} or {@link TextToSpeech#ERROR}.
*/
void onInit(int status);
}
继续往下分析的话,首先我们先附上一个TextToSpeech的使用demo程序片段。
TextToSpeech使用示例
........我代表省略..........
textToSpeech = new TextToSpeech(this, this); // 参数Context,TextToSpeech.OnInitListener
}
/**
* 初始化TextToSpeech引擎
* status:SUCCESS或ERROR
* setLanguage设置语言
*/
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.CHINA);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onClick(View v) {
if (textToSpeech != null && !textToSpeech.isSpeaking()) {
textToSpeech.setPitch(0.0f);// 设置音调
textToSpeech.speak(“我是要播放的文字”,
TextToSpeech.QUEUE_FLUSH, null);
}
}
@Override
protected void onStop() {
super.onStop();
textToSpeech.stop(); // 停止tts
textToSpeech.shutdown(); // 关闭,释放资源
}
有这个demo的例子在这里,我们便对TextToSpeech的使用有了基本的了解。然后,我们分析源码便以这个demo的使用调用过程来分析。
首先,当然是新建TextToSpeech对象,我们要看其结构体。然后我们找到了三个,但是对我们用户可见的只有前两个,最后一个是系统内部使用的构造方法。前两个构造方法的区别就是,前者使用系统默认的TTS引擎,后者可以指定包名为String engine名字的TTS引擎。
public TextToSpeech(Context context, OnInitListener listener) {
this(context, listener, null);
}
public TextToSpeech(Context context, OnInitListener liste