Android中如何使用TextToSpeech
在Android中使用TextToSpeech,首先需要在`AndroidManifest.xml`文件中添加以下权限:
```xml
```
然后在Activity中,初始化TextToSpeech对象,并实现`TextToSpeech.OnInitListener`接口:
```java
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(this, this);
}
@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("TTS", "Language not supported");
}
} else {
Log.e("TTS", "Initialization failed");
}
}
public void speakText(View view) {
String text = "Hello, world!";
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
@Override
protected void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
}
```
在布局文件中,添加一个按钮,点击按钮时调用`speakText()`方法:
```xml
TOP