android实现语音识别
时间: 2023-09-12 08:03:23 浏览: 99
Android实现语音识别可以使用Android提供的SpeechRecognizer类。下面是一个基本的示例代码:
1. 添加权限
在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
```
2. 实现语音识别
在需要实现语音识别的Activity中,实例化SpeechRecognizer类,并调用startListening()方法开启语音识别:
```java
public class MainActivity extends AppCompatActivity {
private SpeechRecognizer speechRecognizer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
speechRecognizer.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) {
String result = matches.get(0);
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
});
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
speechRecognizer.startListening(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (speechRecognizer != null) {
speechRecognizer.destroy();
}
}
}
```
在上面的代码中,我们首先实例化SpeechRecognizer类,并设置RecognitionListener监听器。在onResults()方法中,我们可以获取到语音识别的结果,并将其显示在Toast中。最后,我们使用Intent启动语音识别,并在startListening()方法中传入intent参数。
需要注意的是,在Activity销毁时,应该调用speechRecognizer.destroy()方法,以释放资源。
以上是一个基本的语音识别示例,你可以根据实际需求进行修改和扩展。
阅读全文