TextToSpeech用法
首先假定有一个textview和一个button,点击这个button系统使用tts播放声音。
-
初始化tts:
// 参数Context,TextToSpeech.OnInitListener mTextToSpeech = TextToSpeech(this, this).apply{ // 设置音调,值越大声音越尖(女生),值越小则变成男声,1.0是常规 this.setPitch(1.0f) // 设置语速 this.setSpeechRate(0.5f) }
-
在1中的TextToSpeech构造方法的后一个参数,将接口在这个fragment中实现,大致为:
@Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { // setLanguage设置语言 int result = mTextToSpeech.setLanguage(Locale.CHINA); // TextToSpeech.LANG_MISSING_DATA:表示语言的数据丢失 // TextToSpeech.LANG_NOT_SUPPORTED:不支持 if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show(); } } }
-
设置button的点击事件,说出语言:
String text = main_edit_text.getText().toString().trim(); if (TextUtils.isEmpty(text)) { Toast.makeText(this, "请您输入要朗读的文字", Toast.LENGTH_SHORT).show(); return; } // TODO validate success, do something if (mTextToSpeech != null && !mTextToSpeech.isSpeaking()) { /* TextToSpeech的speak方法有两个重载。 // 执行朗读的方法 speak(CharSequence text,int queueMode,Bundle params,String utteranceId); // 将朗读的的声音记录成音频文件 synthesizeToFile(CharSequence text,Bundle params,File file,String utteranceId); 第二个参数queueMode用于指定发音队列模式,两种模式选择 (1)TextToSpeech.QUEUE_FLUSH:该模式下在有新任务时候会清除当前语音任务,执行新的语音任务 (2)TextToSpeech.QUEUE_ADD:该模式下会把新的语音任务放到语音任务之后, 等前面的语音任务执行完了才会执行新的语音任务 */ mTextToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null); }
-
不过在API 21之后,上述使用的3个参数的speak方法被标记 @deprecated ,所以如下解决:
String text = editText.getText().toString(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { tts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null); } else { tts.speak(text, TextToSpeech.QUEUE_FLUSH, null); }