Android提供了自动朗读支持。可以对指定文本内容进行朗读,从而发生声音;还允许把文本对应的音频录制成音频文件,保存到本地,方便以后播放。Android的自动朗读主要通过TextToSpeech来完成。
构造器如:TextToSpeech(Context context, TextToSpeech.OnInitListennet listener);当创建TextToSpeech对象时,必须先提供一个OnInitListener监听器——负责监听TextToSpeech的初始化结果。
1.代码
1.1.布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical">
<TextView
android:id="@+id/txt_content"
android:layout_width="match_parent"
android:layout_height="90dp"
android:gravity="center"
android:text="播放声音"
android:textColor="#339BFF"
android:textSize="14sp" />
<TextView
android:id="@+id/txt_contents"
android:layout_width="match_parent"
android:layout_height="90dp"
android:gravity="center"
android:text="保存文本"
android:textColor="#339BFF"
android:textSize="14sp" />
</LinearLayout>
1.2.java代码
TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
TextView txt_contents = (TextView) view.findViewById(R.id.txt_contents);
textToSpeech = new TextToSpeech(MyFragment1.this.getContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == textToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE
&& result != TextToSpeech.LANG_AVAILABLE){
Toast.makeText(MyFragment1.this.getContext(), "TTS暂时不支持这种语音的朗读!",
Toast.LENGTH_SHORT).show();
}
}
}
});
//播放语音
txt_content.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.speak(content, TextToSpeech.QUEUE_ADD, null);
}
});
//保存语音
txt_contents.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HashMap<String, String> myHashRender = new HashMap<>();
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, content);
textToSpeech.synthesizeToFile(content, myHashRender,
"/CDSP/pictures/sound.wav");
Toast.makeText(MyFragment1.this.getContext(), "声音记录成功。", Toast.LENGTH_SHORT).show();
}
});
2.效果图
3.核心代码讲解
使用TextToSpeech的步骤如下:
创建TextToSpeech对象,创建时传入OnInitListener监听器监听示范创建成功。
设置TextToSpeech所使用语言国家选项,通过返回值判断TTS是否支持该语言、国家选项。
调用speak()或synthesizeToFile方法。
关闭TTS,回收资源。