1. 说明
以下例程功能为:在应用程序中使用通于访问service调用语言识别功能,录音并识别后将识别的字串通过Listener返回给应用程序。注意:使用前需要安装语音识别服务,如编译安装源码中的development/samples/VoiceRecogitionService。
2. 本例参考自android源码
a) 后台服务
参见development/samples/VoiceRecognitionService/*
此处实现了一个模拟的后台服务,它并未实现真的语音识别,而只是一个框架以示例,编译并安装它,即可在设置的语音输入与输出中看到它,它包含了一个设置界面,当连接这个Service时,如果设置了Letters,则直接返回abc,如果设置了Numbers,则直接返回123
你可以自己实现,用于连接android源码自带的识别引擎srec.
b) 前台程序
参见frameworks/base/core/java/android/speech/Recognition*
它与后台Service交互,此段代码实现在应用程序界面中
3. 可从此处下载可独立运行的代码(前台程序):
http://download.csdn.net/source/2591401
4. 核心代码及说明
- package com.android.mystt3;
-
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.speech.RecognitionListener;
- import android.speech.RecognizerIntent;
- import android.speech.SpeechRecognizer;
- import android.widget.Button;
- import android.widget.TextView;
- import java.util.ArrayList;
- import android.util.Log;
-
- public class MyStt3Activity extends Activity implements OnClickListener {
- private TextView mText;
- private SpeechRecognizer sr;
- private static final String TAG = "MyStt3Activity";
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button speakButton = (Button) findViewById(R.id.btn_speak);
- mText = (TextView) findViewById(R.id.text);
- speakButton.setOnClickListener(this);
- sr = SpeechRecognizer.createSpeechRecognizer(this);
- sr.setRecognitionListener(new listener());
- }
-
- class listener implements RecognitionListener
- {
- public void onReadyForSpeech(Bundle params)
- {
- Log.d(TAG, "onReadyForSpeech");
- }
- public void onBeginningOfSpeech()
- {
- Log.d(TAG, "onBeginningOfSpeech");
- }
- public void onRmsChanged(float rmsdB)
- {
- Log.d(TAG, "onRmsChanged");
- }
- public void onBufferReceived(byte[] buffer)
- {
- Log.d(TAG, "onBufferReceived");
- }
- public void onEndOfSpeech()
- {
- Log.d(TAG, "onEndofSpeech");
- }
- public void onError(int error)
- {
- Log.d(TAG, "error " + error);
- mText.setText("error " + error);
- }
-
- public void onResults(Bundle results)
- {
- String str = new String();
- Log.d(TAG, "onResults " + results);
- ArrayList<String> data = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
- for (int i = 0; i < data.size(); i++)
- {
- Log.d(TAG, "result " + data.get(i));
- str += data.get(i);
- }
- mText.setText(str);
- }
- public void onPartialResults(Bundle partialResults)
- {
- Log.d(TAG, "onPartialResults");
- }
- public void onEvent(int eventType, Bundle params)
- {
- Log.d(TAG, "onEvent " + eventType);
- }
- }
- public void onClick(View v) {
- if (v.getId() == R.id.btn_speak) {
- sr.startListening(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH));
- }
- }
- }
(转载请注明出处: http://xy0811.spaces.live.com/)
(xy0811) |