在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官方文档。