SpeechRecognizer导致ANR ......我需要Android语音API的帮助

tnu*_*mak 12 android speech-to-text android-service

编辑:我应该已经提到过这个,但我在服务中运行此代码.整个应用程序由小部件按钮打开/关闭,没有任何活动.


更新:我尝试将SDK源附加到项目中,这样我就可以更准确地了解发生故障的位置,但从外观来看,只包含公共API,这似乎使它们的用处更少.任何人都可以建议至少一种调试方法来解决这个问题吗?我有点卡住了.


我正在尝试使用Android的语音识别软件包来记录用户语音并将其翻译成文本.不幸的是,当我尝试启动监听时,我收到的ANR错误并未指出任何具体内容.

正如SpeechRecognizer API指示的那样,如果您尝试从主线程调用它,则抛出RuntimeException.这会让我想知道处理是否过于苛刻......但我知道其他应用程序使用Android API就可以实现这一目的,而且它通常非常活泼.

java.lang.RuntimeException: SpeechRecognizer should be used only from the application's main thread

这是我试图从我的服务中调用的代码的一个(修剪过的)示例.这是正确的方法吗?

感谢您抽出宝贵时间提供帮助.这是一个我无法克服的障碍.

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
        "com.domain.app");

SpeechRecognizer recognizer = SpeechRecognizer
        .createSpeechRecognizer(this.getApplicationContext());
RecognitionListener listener = new RecognitionListener() {
    @Override
    public void onResults(Bundle results) {
        ArrayList<String> voiceResults = results
                .getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
        if (voiceResults == null) {
            Log.e(getString(R.string.log_label), "No voice results");
        } else {
            Log.d(getString(R.string.log_label), "Printing matches: ");
            for (String match : voiceResults) {
                Log.d(getString(R.string.log_label), match);
            }
        }
    }

    @Override
    public void onReadyForSpeech(Bundle params) {
        Log.d(getString(R.string.log_label), "Ready for speech");
    }

    @Override
    public void onError(int error) {
        Log.d(getString(R.string.log_label),
                "Error listening for speech: " + error);
    }

    @Override
    public void onBeginningOfSpeech() {
        Log.d(getString(R.string.log_label), "Speech starting");
    }
};
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
Run Code Online (Sandbox Code Playgroud)

小智 5

确保使用RECORD_AUDIO权限。


sat*_*ine 4

您不需要自己创建 SpeechRecognizer 类,也不需要实现 RecognizerListener。谷歌将它们公开是为了友善,但它们看起来相当复杂,可能仅供专家使用。

要从用户语音中获取文本,您只需使用 RecognizerIntent.ACTION_RECOGNIZE_SPEECH 启动内置语音识别器 Activity,然后等待结果在 onActivityResult 中返回。看一下这里的示例代码:

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.html

我从这篇文章中摘下来的。

http://developer.android.com/resources/articles/speech-input.html

祝你好运。