这是一个很简单的语音搜索Demo,要使用语音搜索,前提是必须安装Google Voice Search Engine,以下是主要代码:
package com.mjl.speechsearch;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity {
/** Called when the activity is first created. */
private Button button = null;
public static final int voice = 0x1008;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PackageManager pm = getPackageManager();
//查询有无安装Google Voice Search Engine
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
//若有安装Google Voice Search Engine
if(activities.size()!=0){
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);
}else{
Toast.makeText(Main.this, "没有安装 Google Search Engine", Toast.LENGTH_LONG).show();
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode){
case voice:
if(requestCode == voice&&resultCode == RESULT_OK){
String strRet = "";
//取得识别结果
ArrayList<String>results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(int i = 0; i<results.size(); i++){
strRet += results.get(i);
}
if(strRet.length()>0){
Toast.makeText(Main.this, strRet, Toast.LENGTH_LONG).show();
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
search.putExtra(SearchManager.QUERY, strRet);
final Bundle appData = getIntent().getBundleExtra(SearchManager.APP_DATA);
if(appData != null){
search.putExtra(SearchManager.APP_DATA, appData);
}
startActivity(search);
}else{
Toast.makeText(Main.this, "Can not recoginze...", Toast.LENGTH_LONG).show();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
}