Android中使用TTS(TextToSpeech)將文字轉為語音
阿新 • • 發佈:2019-02-07
實現步驟:
- 建立TextToSpeech物件,建立時傳入OnInitListener監聽器
- 設定TextToSpeech所使用的語言、國家選項
- 呼叫speak()或synthesizeToFile方法
- 關閉TTS,回收資源
- 在佈局中加入EditText用於獲取文字,加入Button用於控制播放或儲存合成的聲音檔案
- 程式碼:
- 初始化
TextToSpeech textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {
Toast.makeText(MainActivity.this , "暫不支援該語言", Toast.LENGTH_SHORT).show();
}
}
}
});
- 播放或儲存為檔案
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@TargetApi(Build.VERSION_CODES.LOLLIPOP )
@Override
public void onClick(View view) {
textToSpeech.setSpeechRate(1);
textToSpeech.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null, "speech");
Snackbar.make(view, "是否儲存該聲音檔案", Snackbar.LENGTH_LONG)
.setAction("儲存", new View.OnClickListener() {
@Override
public void onClick(View v) {
textToSpeech.synthesizeToFile(editText.getText().toString(), null, new File("/mnt/sdcard/sound.mp3"), "record");
Toast.makeText(MainActivity.this, "儲存成功", Toast.LENGTH_SHORT).show();
}
}).show();
}
});
- 回收資源
protected void onDestroy() {
super.onDestroy();
if (textToSpeech != null) {
textToSpeech.shutdown();
}
}