我在Android中使用SpeechRecognizer和RecognizerIntent來實現語音識別。我的目標是在我的語音識別器在屏幕上顯示結果後,重新開始收聽語音。爲此,我使用下面的代碼。SpeechRecognizer在第一個結果後沒有聽到
問題是,第一次運行正常並顯示結果,但在第二次開始監聽後(從onResults方法調用),它沒有聽到出於某種原因正在發言的內容。然後它給出一個ERROR_SPEECH_TIMEOUT錯誤,這意味着沒有語音輸入。在Logcat上,我可以看到它進入onReadyForSpeech(),但不知何故,它不會聽到我在說什麼。
有誰知道爲什麼會發生這種情況?它返回結果後是否繼續收聽?明確再次調用startListening是否正確? 「
public class VR extends Activity implements RecognitionListener {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private TextView vrtext;
private SpeechRecognizer speech = null;
private Intent intent;
private String TAG = "VR";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr);
vrtext = (TextView) findViewById(R.id.vrtext);
}
@Override
public void onResume()
{
listen();
super.onResume();
}
private void listen()
{
speech = SpeechRecognizer.createSpeechRecognizer(this);
speech.setRecognitionListener(this);
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en");
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
speech.startListening(intent);
}
@Override
protected void onPause() {
super.onPause();
// TODO Auto-generated method stub
if(speech != null)
{
speech.destroy();
Log.i(TAG,"destroy");
}
}
public void onBeginningOfSpeech() {
// TODO Auto-generated method stub
Log.i(TAG, "onbeginningofspeech");
}
public void onBufferReceived(byte[] arg0) {
// TODO Auto-generated method stub
//Log.i(TAG, "onbufferreceived");
}
public void onEndOfSpeech() {
// TODO Auto-generated method stub
Log.i(TAG, "onendofspeech");
}
public void onError(int arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "error code: " + arg0);
}
public void onEvent(int arg0, Bundle arg1) {
// TODO Auto-generated method stub
Log.i(TAG, "onevent");
}
public void onPartialResults(Bundle arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "onpartialresults");
}
public void onReadyForSpeech(Bundle arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "onreadyforspeech");
}
public void onResults(Bundle arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "onresults");
ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String s = "";
for (String result:matches)
s += result + "\n";
vrtext.setText(s);
speech.startListening(intent);
}
public void onRmsChanged(float arg0) {
// TODO Auto-generated method stub
//Log.i(TAG, "onrmschanged");
}
}
您正在調用'listen'而不清洗前面的演講對象。在調用listen方法之前,最好調用語音對象的'destroy()'。 –