2011年5月5日星期四

啟動 Android 的語音識別(Speech Recognition)功能

應用軟件可以通過 RecognizerIntent, 啟動 Android 的語音識別(Speech Recognition)功能.

Android 的語音識別(Speech Recognition)功能
Android 的語音識別(Speech Recognition)功能

例子:
package com.AndroidSpeechRecognition;

import java.util.ArrayList;

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

public class AndroidSpeechRecognition extends Activity {

private static final int RQS_VOICE_RECOGNITION = 1;
TextView textResult;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonSpeech = (Button)findViewById(R.id.Speech);
textResult = (TextView)findViewById(R.id.Result);

buttonSpeech.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Start Speech");
startActivityForResult(intent, RQS_VOICE_RECOGNITION);
}});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == RQS_VOICE_RECOGNITION){
if(resultCode == RESULT_OK){

ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String firstMatch = (String)result.get(0);
textResult.setText(firstMatch);
}
}


}
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/Speech"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Speech"
/>
<TextView
android:id="@+id/Result"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>



相關文章:
- 處理語音識別返回的字符串數組列表

4 則留言: