Android sdk提供了语音识别的接口,有些人在网上找了例子发现运行不了(PS:网上的例子基本就那一个,都是各种转载的),原因在于手机没有安装google语音搜索软件!去网上下载一个安上就可以了,另外需保持手机网络畅通。
第一种方法:这种方法会显示一个语音对话框,各种提示信息会显示的比较清晰,也是实现起来最简单的。
触发语音识别是调用
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "您的语音将转化为文字"); startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
VOICE_RECOGNITION_REQUEST_CODE这个是一个静态的全局变量
sdk解释是:requestCode If>= 0, this code will be returned in onActivityResult() when the activity exits.
然后复写onActivityResult()方法:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK){ ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); Toast.makeText(MainActivity.this, matches.get(0), Toast.LENGTH_LONG).show(); //to do sth } super.onActivityResult(requestCode, resultCode, data); }
第2中方法:这种方法是不显示对话框,完全在后台运行,给用户的体验会更好一些。
初始化:
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this); recognizer.setRecognitionListener(new listener());
触发语音识别时调用
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra("calling_package", "VoiceIME"); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1); recognizer.startListening(intent);
区别于第一种方法,这种方法要实现一个接口RecognitionListener类
class listener implements RecognitionListener { public void onReadyForSpeech(Bundle params) { } public void onBeginningOfSpeech() { } public void onRmsChanged(float rmsdB) { } public void onBufferReceived(byte[] buffer) { } public void onEndOfSpeech() { } public void onError(int error) { String s = ""; switch(error){ case SpeechRecognizer.ERROR_AUDIO: s = "录音设别错误"; break; case SpeechRecognizer.ERROR_CLIENT: s = "其他客户端错误"; break; case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS: s = "权限不足"; break; case SpeechRecognizer.ERROR_NETWORK: s = "网络连接错误"; break; case SpeechRecognizer.ERROR_NETWORK_TIMEOUT: s = "网络连接超时"; break; case SpeechRecognizer.ERROR_NO_MATCH: s = "没有匹配项"; break; case SpeechRecognizer.ERROR_RECOGNIZER_BUSY: s = "识别服务繁忙"; break; case SpeechRecognizer.ERROR_SERVER: s = "识别服务器错误"; break; case SpeechRecognizer.ERROR_SPEECH_TIMEOUT: s = "无语音输入"; break; } s += " 请重试"; Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show(); } public void onResults(Bundle results) { recognizer_result = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION).get(0); Toast.makeText(MainActivity.this, recognizer_result, Toast.LENGTH_SHORT).show(); } public void onPartialResults(Bundle partialResults) { } public void onEvent(int eventType, Bundle params) { } }