Android语音识别

Android由于有了Google的支持,那么他的语音识别做起来也是比较简单的,主要是调用谷歌的语音识别软件,然后取得他的返回值,谷歌的语音识别有着极其庞大的云中心以及数据库。当然语音识别是存在一个精度问题的,所以谷歌语音识别软件的返回值不是唯一的,因此到时候需要自己做筛选或者处理:package com.ichances.voice;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class VoiceActivity extends Activity {
	/** Called when the activity is first created. */
	private Button btnReconizer;
	private static final int VOICE_RECOGNITION_REQUEST_CODE =618;
	private TextView resText;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btnReconizer = (Button) this.findViewById(R.id.button1);
		resText = (TextView) findViewById(R.id.restext);
		btnReconizer.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				try {
					// 通过Intent传递语音识别的模式,开启语音
					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);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					Toast.makeText(getApplicationContext(), "找不到语音设备", 1)
							.show();
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// 回调获取从谷歌得到的数据
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE
				&& resultCode == RESULT_OK) {
			// 取得语音的字符
			ArrayList<String> results = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			String resultString = "";
			for (int i = 0; i < results.size(); i++) {
				resultString += String.valueOf(i + 1) + ":" + results.get(i)
						+ ";";
				Log.i("结果", resultString);
			}
			resText.setText(resultString);
			Toast.makeText(this, resultString, 1).show();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}

相关推荐