这里直接介绍使用方法,一看就会
首先实例化TextToSpeech语音对象
//实例化自带语音对象
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == textToSpeech.SUCCESS) {
//判断是否支持下面两种语言(英文/中文)
int result1 = textToSpeech.setLanguage(Locale.US);
int result2 = textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE);
boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);
Log.i("TTS", "US是否支持?--》" + a + "\nzh-CN是否支持?--》" + b);
} else {
Toast.makeText(MainActivity.this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
}
}
});
可以写一个调用方法,直接把要朗读的内容带进去在需要朗读的地方调用
private void startTTS(String data) {
// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
textToSpeech.setPitch(0.1f);
// 设置语速
textToSpeech.setSpeechRate(1.5f);
//输入中文,若不支持的设备则不会读出来
textToSpeech.speak(data,TextToSpeech.QUEUE_FLUSH, null);
}
最后就是使用了,直接在需要朗读的地方调用
startTTS("床前明月光,疑是地上霜,举头望明月,低头思故乡。");
别忘记在使用完之后关闭释放资源
@Override
protected void onStop() {
super.onStop();
textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
textToSpeech.shutdown(); // 关闭,释放资源
}
下面是完整的代码用来参考
public class MainActivity extends AppCompatActivity {
private Button mLook;
private TextToSpeech textToSpeech = null;//创建自带语音对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLook = findViewById(R.id.look);
initTTS();
mLook.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startTTS("床前明月光,疑是地上霜,举头望明月,低头思故乡。");
}
});
}
private void initTTS() {
//实例化自带语音对象
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == textToSpeech.SUCCESS) {
textToSpeech.setPitch(1.0f);//方法用来控制音调
textToSpeech.setSpeechRate(1.0f);//用来控制语速
//判断是否支持下面两种语言(英文/中文)
int result1 = textToSpeech.setLanguage(Locale.US);
int result2 = textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE);
boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);
Log.i("TTS", "US是否支持?--》" + a + "\nzh-CN是否支持?--》" + b);
} else {
Toast.makeText(MainActivity.this, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
}
}
});
}
private void startTTS(String data) {
// 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规
textToSpeech.setPitch(0.1f);
// 设置语速
textToSpeech.setSpeechRate(1.5f);
//输入中文,若不支持的设备则不会读出来
textToSpeech.speak(data,TextToSpeech.QUEUE_FLUSH, null);
}
@Override
protected void onStop() {
super.onStop();
textToSpeech.stop(); // 不管是否正在朗读TTS都被打断
textToSpeech.shutdown(); // 关闭,释放资源
}
}
但是TTS系统默认是不支持中文的,只能进行英文发音,当然也不是没有解决办法,只要在本地安装一个支持中文发音的语音包插件就ok了
下载上面的语音包,解压出来是个apk文件,安装到手机上即可
实现短促音效请看Android点击按钮触发音效