Android 语音识别示例

一个简单调用语音识别的程序,

注意,必须在使用程序前先安装goole语音搜索

public class MainActivity extends Activity {
   SpeechRecognizer sr;
   Button speak;
   Button done;
	/**在mainfest.xml中必须添加权限
	 *    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
	 * 
	 * */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sr=SpeechRecognizer.createSpeechRecognizer(this);//init
        speak=(Button)findViewById(R.id.button1);
        done=(Button)findViewById(R.id.button2);
        done.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
			   sr.stopListening();	//停止监听,开始识别
			}
		});
        speak.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);  
				intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);//返回匹配数据条数。   
			
				sr.startListening(intent);//开始监听语音
			}
		});
        
        sr.setRecognitionListener(new RecognitionListener() {
			
			public void onRmsChanged(float rmsdB) {
				// TODO Auto-generated method stub
				Log.i("debug", "rmsChange---------------"+rmsdB);
			}
			
			public void onResults(Bundle results) {
				// TODO Auto-generated method stub
				//返回识别数据
				StringBuilder result=new StringBuilder();
				ArrayList<String> lists=results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
				for (String string : lists) {
					result.append(string);
				}
				Toast.makeText(getApplication(), result.toString(), 1000).show();
				Log.i("debug","result-----------"+ result.toString());
			}
			
			public void onReadyForSpeech(Bundle params) {
				// TODO Auto-generated method stub
				Log.i("debug", "onReadyForSpeech---------------");
			}
			
			public void onPartialResults(Bundle partialResults) {
				// TODO Auto-generated method stub
				Log.i("debug", "onPartialResults---------------");
			}
			
			public void onEvent(int eventType, Bundle params) {
				// TODO Auto-generated method stub
				Log.i("debug", "onEvent---------------"+eventType);
			}
			
			public void onError(int error) {
				// TODO Auto-generated method stub
				Log.i("debug", "onError---------------"+error);
			}
			
			public void onEndOfSpeech() {
				// TODO Auto-generated method stub
				Log.i("debug", "onEndOfSpeech---------------");
			}
			
			public void onBufferReceived(byte[] buffer) {
				// TODO Auto-generated method stub
				Log.i("debug", "onBufferReceived---------------");
			}
			
			public void onBeginningOfSpeech() {
				// TODO Auto-generated method stub
				Log.i("debug", "onBeginningOfSpeech---------------");
			}
		});
    }
   @Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		sr.destroy();//
	}








   

你可能感兴趣的:(Android 语音识别示例)