在Android中使用TextToSpeech的方法如下:
dependencies {
implementation 'com.android.support:support-v4:YOUR_VERSION'
implementation 'com.android.support:appcompat-v7:YOUR_VERSION'
implementation 'com.google.android.gms:play-services-ads:YOUR_VERSION'
}
private TextToSpeech textToSpeech;
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
// TextToSpeech初始化成功
} else {
Log.e("TextToSpeech", "初始化失敗");
}
}
});
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TextToSpeech", "不支持該語言");
}
} else {
Log.e("TextToSpeech", "初始化失敗");
}
}
textToSpeech.speak("Hello, World!", TextToSpeech.QUEUE_FLUSH, null);
這是一個基本的使用TextToSpeech的例子。你還可以設置其他參數,如語速、音調等。詳細的文檔和其他方法,請查閱Android官方文檔。