|
|||||
音声認識(RecognizerIntent)Androidでは音声認識も簡単に利用できる。ACTION_RECOGNIZE_SPEECHを指定してIntentを生成し、putExtraメソッドでEXTRA_LANGUAGE_MODELを設定する。今回は認識した音声を文字列で返すLANGUAGE_MODEL_FREE_FORMに設定する。 音声認識の際にマイクのプロンプトが表示されるが、これに任意の文字列を表示するためにputExtraメソッドでEXTRA_PROMPTを設定することもできる。後はstartActivityForResultメソッドでこのIntentを渡して音声認識を開始する。
package biz.office_matsuanga.android;
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 RecognizerIntentTestActivity extends Activity {
static final int RECOGNIZE_SPEECH_REQUEST = 0;
Button button1;
TextView textView1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView1.setText("");
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, RECOGNIZE_SPEECH_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == RECOGNIZE_SPEECH_REQUEST && resultCode == RESULT_OK) {
// 複数の候補が返される
ArrayList<String> candidates = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String recognizedStrings = "";
for(String str: candidates) {
recognizedStrings += str + "\n";
}
textView1.setText(recognizedStrings);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
音声認識の結果はActivityのonActivityResultメソッドで受け取る。onActivityResultメソッドは他のIntentの結果も受け取ることができるのでrequestCodeで識別する。RecognizerIntentの場合、結果をgetStringArrayListExtraメソッドでArrayListに抽出する。 (2012/02/15)
Copyright(C) 2004-2013 モバイル開発系(K) All rights reserved.
[Home]
|
|||||