如何在android中等待语音识别的结果?

时间:2015-04-01 12:16:28

标签: android android-asynctask speech-recognition android-speech-api

我在android中使用识别监听器进行语音识别。我班的基本结构如下:

class SpeechInput implements RecognitionListener {

    Intent intent;
    SpeechRecognizer sr;
    boolean stop;

    public void init() {
        sr = SpeechRecognizer.createSpeechRecognizer(context);
        sr.setRecognitionListener(this);
        intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,context.getPackageName());
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,3);
    }

    ...

}

我陷入了一种情况,我想在一个循环中运行android识别监听器,其中包括:

for(int i=0; i<N; i++) {
       // Some processing code
       sr.startListening(intent);
}

现在,我想在再次开始侦听之前等待输出。为了实现这一点,我尝试使用锁定机制如下:

for(int i=0; i<N; i++) {
       // Some processing code
       sr.startListening(intent);
       stop = false; 
       new Task().execute().get();
}

其中Task是asyncTask,定义如下:

private class Task extends AsyncTask<Void,Void,Void> {

        @Override
    protected Void doInBackground(Void... params) {
        try {
            int counter = 0;
            while(!stop) {
                counter++;
            }
        } catch(Exception e) {
        }
        return null;
    }
}

布尔值'stop'在RecognitionListener的'onResults'方法中更新,如下所示:

public void onResults(Bundle results) {
    ...
    stop = true;
}

问题在于语音识别根本不起作用。什么都没发生,甚至没有开始。我想这是因为asyncTask占用了所有处理器时间。你能指导我走向一个能够实现这个目标的架构吗?谢谢。

2 个答案:

答案 0 :(得分:3)

收到结果后重新开始收听。无需循环,无需等待。

我不是Android上的语音识别专家,但您可能会通过调用阻止主线程

new Task().execute().get();

因此语音识别可能永远不会开始。

答案 1 :(得分:3)

值得注意的是,Android 的语音识别API方法只能从主线程调用,所有回调都在应用程序的主线程上执行。

因此,当主线程被阻塞时,识别侦听器也会被阻塞,这就是当我尝试按照问题中显示的方式执行语音识别时没有任何反应的原因。

从接受的答案中获取提示,我使用onResults接口的RecognitionListener方法重启监听器,如下所示:

public void onResults(Bundle results) {
    ...
    sr.startListening(intent);
}