android 语音识别方法二:应用程序自己调用语音识别库

#移动开发 #Android

1. 说明
以下例程功能为:应用程序自身调用语言识别函数,程序以循环方式等待录音并识别后的字串。

2. 本例参考自 android 代码: frameworks/base/core/java/android/speech/srec/Recognizer.java 中注释部分

3. 可从此处下载可独立运行的代码: [http://download.csdn.net/source/2591401

](http://download.csdn.net/source/2591401)

4. 核心代码及说明

_ package com.android.mystt2; _

_ _

_ import android.app.Activity; _

_ import android.content.Intent; _

_ import android.os.Bundle; _

_ import android.widget.Button; _

_ import android.widget.TextView; _

_ import android.view.View; _

_ import android.view.View.OnClickListener; _

_ _

_ import android.speech.srec.Recognizer; _

_ import android.speech.srec.MicrophoneInputStream; _

_ import java.io.InputStream; _

_ import java.io.IOException; _

_ import android.util.Log; _

_ _

_ public class MyStt2Activity extends Activity implements OnClickListener { _

_ private TextView mText; _

_ 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); _

_ } _

_ _

_ public void onClick(View v) { _

_ if (v.getId() == R.id.btn_speak) { _

_ test(); _

_ } _

_ } _

_ _

_ void test() { _

_ try { _

_ InputStream audio = new MicrophoneInputStream(11025, 11025 * 5); // _ _

设置输入参数 _ __

_ String cdir = Recognizer.getConfigDir(null); // _ _ 获取语音识别配置目录 _ __

_ Recognizer recognizer = new Recognizer(cdir + "/baseline11k.par"); _

_ Recognizer.Grammar grammar = recognizer.new Grammar(cdir _

_ + "/grammars/VoiceDialer.g2g"); _

_ grammar.setupRecognizer(); _

_ grammar.resetAllSlots(); _

_ grammar.compile(); _

_ recognizer.start(); // _ _ 开始识别 _ __

_ while (true) { // _ _ 循环等待识别结果 _ __

_ switch (recognizer.advance()) { _

_ case Recognizer.EVENT_INCOMPLETE: _

_ case Recognizer.EVENT_STARTED: _

_ case Recognizer.EVENT_START_OF_VOICING: _

_ case Recognizer.EVENT_END_OF_VOICING: _

_ continue; // _ _ 未完成,继续等待识别结果 _ __

_ case Recognizer.EVENT_RECOGNITION_RESULT: _

_ for (int i = 0; i < recognizer.getResultCount(); i++) { _

_ String result = recognizer.getResult(i, _

_ Recognizer.KEY_LITERAL); _

_ Log.d(TAG, "result " + result); _

_ mText.setText(result); _

_ } // _ _ 识别到字串,显示并退出循环 _ __

_ break; _

_ case Recognizer.EVENT_NEED_MORE_AUDIO: _

_ recognizer.putAudio(audio) // _ _ 需要更多音频数据 _ ;

_ continue; _

_ default: _

_ break; _

_ } _

_ break; _

_ } _

_ recognizer.stop(); _

_ recognizer.destroy(); _

_ audio.close(); // _ _ 回收资源 _ __

_ } catch (IOException e) { _

_ Lo _ _ g.d(TAG, "error", e); _

_ _ _ mText.setText("error " + e); _

_ } _

_ } _

_ } _

__

_

_ (转载请注明出处: http://xy0811.spaces.live.com/

) _

_ _

_