我使用以下代码通过google调用语音识别器:
// This is a demonstration of Android's built in speech recognizer
package com.example.voiceinputbuiltintest;
import java.util.ArrayList;
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int VOICE_RECOGNITION = 1;
Button speakButton ;
TextView spokenWords;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speakButton = (Button) findViewById(R.id.button1);
spokenWords = (TextView)findViewById(R.id.textView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {
if (requestCode == VOICE_RECOGNITION && resultCode == RESULT_OK) {
ArrayList<String> results;
results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
// TODO Do something with the recognized voice strings
Toast.makeText(this, results.get(0), Toast.LENGTH_SHORT).show();
spokenWords.setText(results.get(0));
}
super.onActivityResult(requestCode, resultCode, data);
}
public void btnSpeak(View view){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify free form input
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Please start speaking");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
startActivityForResult(intent, VOICE_RECOGNITION);
}
}
这在我的测试机器中没有网络连接,这是带有Android 4.3的Nexus 7。我认为它可以在任何Android设备上工作相同。但是,当我在三星Galaxy S2上使用Android版本gingerbread.el21进行尝试时,语音识别器活动会显示出来,但是说它需要网络连接并且拒绝工作。为什么它在Nexus 7中工作而在Galaxy S2中不起作用?它是脱机工作还是需要网络连接?即使我停止了无线网络,它也能在Nexus 7中运行。
答案 0 :(得分:11)