要使用Android的TextToSpeech服务,首先需要在AndroidManifest.xml文件中添加以下权限:
然后,在你的Activity中,你需要初始化TextToSpeech对象,并实现TextToSpeech.OnInitListener接口。
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import java.util.HashMap;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
tts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
// TTS starts speaking
}
@Override
public void onDone(String utteranceId) {
// TTS finishes speaking
}
@Override
public void onError(String utteranceId) {
// TTS encounters an error
}
});
speakOut("Hello, World!");
}
} else {
Log.e("TTS", "Initialization Failed!");
}
}
private void speakOut(String text) {
String utteranceId = this.hashCode() + "";
HashMap params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, params, utteranceId);
}
@Override
protected void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
在上面的示例代码中,我们首先在onCreate()
方法中实例化TextToSpeech对象,并传入this
和this
作为参数,以便在对象初始化成功后调用onInit()
方法。
在onInit()
方法中,我们设置了TextToSpeech的语言为英语,然后添加了一个UtteranceProgressListener,用于监听TTS的状态。最后,我们调用speakOut()
方法,传入要朗读的文本。
speakOut()
方法用于将文本传递给TTS引擎并朗读出来。我们使用hashCode()
作为utteranceId,以确保每次调用speakOut()
都生成一个唯一的utteranceId。我们还可以通过params
参数传递其他参数,例如设置语速、音量等。
最后,在onDestroy()
方法中,我们停止TTS引擎并释放资源。