在API Level 22中,可以使用TextToSpeech类来将文本转换为语音。以下是一个基本的示例代码,演示如何实现这一功能:
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
private TextToSpeech textToSpeech;
private boolean isTtsInitialized = false;
textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
isTtsInitialized = true;
// 设置语言
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
} else {
Log.e("TTS", "Initialization failed");
}
}
});
@Override
protected void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
private void speakText(String text) {
if (isTtsInitialized) {
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, "UniqueID");
}
}
speakText("Hello, world!");
注意:这只是一个基本示例,可以在此基础上进行扩展和自定义。另外,需要确保设备上安装了TTS引擎,否则可能无法正常运行。