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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class AndroidSpeechRecognition extends Activity {
private static final int RQS_VOICE_RECOGNITION = 1;
TextView textResult;
ListView listResult;
/** 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);
listResult = (ListView)findViewById(R.id.ResultList);
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);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, result);
listResult.setAdapter(arrayAdapter);
listResult.setOnItemClickListener(listResultOnItemClickListener);
}
}
}
private OnItemClickListener listResultOnItemClickListener
= new ListView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
// TODO Auto-generated method stub
String selectedResult = adapter.getItemAtPosition(position).toString();
textResult.setText(selectedResult);
}};
}
2011年5月5日星期四
處理語音識別返回的字符串數組列表
從上文"啟動 Android 的語音識別(Speech Recognition)功能"可以注意到所返回的結果是一個字符串數組列表(StringArrayList). 我們可以使用列表視圖(ListView)顯示所有返回的結果, 以供用戶選擇最正確的答案.
訂閱:
發佈留言 (Atom)
沒有留言:
發佈留言