android studio 简单对话功能
时间: 2023-06-29 21:20:51 浏览: 97
要在 Android Studio 中实现简单的对话功能,可以使用 Android 自带的 TextToSpeech 和 SpeechRecognizer 类。
TextToSpeech 可以将文本转换为语音,SpeechRecognizer 可以将语音转换为文本。
以下是一个简单的示例代码,可以在用户说出“你好”时使用 TextToSpeech 来回复“你好”:
```
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);
// 初始化 TextToSpeech 对象
tts = new TextToSpeech(this, this);
// 初始化 SpeechRecognizer 对象
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
// 获取识别结果
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (matches != null && matches.size() > 0) {
String text = matches.get(0);
if ("你好".equals(text)) {
// 回复“你好”
tts.speak("你好", TextToSpeech.QUEUE_FLUSH, null);
}
}
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
});
// 开始识别语音
recognizer.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
// 设置语音引擎
int result = tts.setLanguage(Locale.CHINA);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
} else {
Log.e("TTS", "Init failed");
}
}
@Override
protected void onDestroy() {
// 释放 TextToSpeech 资源
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
```
需要注意的是,使用 SpeechRecognizer 时需要用户授权使用麦克风权限。可以在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.RECORD_AUDIO" />
```
阅读全文