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

标签 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;
    }
}

bool 值“stop”在 RecognitionListener 的“onResults”方法中更新如下:

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

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

最佳答案

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

我不是 Android 语音识别方面的专家,但您可能正在通过调用阻塞主线程

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

所以语音识别可能从未开始。

关于android - 如何在android中等待语音识别的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29390600/

相关文章:

Android 构建系统,NEON 和非 NEON 构建

android - 没有收到 MEDIA_BUTTON 回调

android - 在 Activity 完成之前处理时如何在android Activity 中显示加载消息或对话框或图像?

php - 将 mySQL 与 Android 连接

android - 谷歌语音转文本 : Extra language set to "kn" but not working

android - 如何在android中自动调用我的应用程序

android - 几次运行后,AsyncTask 在 onPreExecute 后停止

java - 在 Android 上将语音转换为文本

objective-c - Mac OS X 语音转文本 API。如何?

java - this.getReadableDatabase() 处出现 NullPointerException;