/*
自动朗读TTS(Text To Speech)
使用4步:
1 new TextToSpeech()对象,需要一个监听器参数(监听TextToSpeech对象初始化状态,实现ini方法,初始完对象回调)
2 设置语言(不支持中文) setLanguage() 如Locale.UK
3 speak()方法朗读 有模式新朗读/追加
4 shutdown()关闭TextToSpeech
*/
public class MainActivity extends Activity {
TextToSpeech textToSpeech;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getContentResolver().registerContentObserver();
editText = (EditText) findViewById(R.id.editText);
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//textToSpeech.getAvailableLanguages();
int result = textToSpeech.setLanguage(Locale.ENGLISH);
if (result != TextToSpeech.LANG_AVAILABLE && result != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
Toast.makeText(MainActivity.this, "不支持该语言", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void write(View view) {
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null);
//待转换文本 播放模式 新任务/追加 音频转换时参数
}
@Override
protected void onDestroy() {
super.onDestroy();
if (textToSpeech != null)
textToSpeech.shutdown();
}
public void record(View view) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
String path = Environment.getExternalStorageDirectory().getCanonicalPath();
textToSpeech.synthesizeToFile(editText.getText().toString(), null, path + "/mysound.wav");
Toast.makeText(MainActivity.this, "save Successful!", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
TextToSpeech自动朗读使用
最新推荐文章于 2024-03-03 14:32:11 发布