您的位置:首页 > 其它

语音识别方法三:使用Service调用语音识别程序

2010-08-03 13:28 447 查看
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 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/)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐