我正在尝试开发具有语音识别功能的cordova应用程序,但我不想使用标准的Google弹出式界面。我基本上使用语音识别插件:http://plugins.cordova.io/#/package/com.manueldeveloper.speech-recognizer,但我想设置一个RecognitionListener并将其用于识别回调。这在使用本教程中的代码开发的本机应用程序中完美运行:http://www.truiton.com/2014/06/android-speech-recognition-without-dialog-custom-activity/。所以我尝试在插件中开发一个类似的解决方案:
Activity a = cordova.getActivity();
SpeechRecognizer sr = SpeechRecognizer.createSpeechRecognizer(a);
sr.setRecognitionListener(new listener());
// Create the intent and set parameters
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
if (maxMatches > 0)
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxMatches);
if (!prompt.equals(""))
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
sr.startListening(intent);
cordova.startActivityForResult(this, intent, REQUEST_CODE);
当我尝试启动语音识别时,我收到一个错误:“SpeechRecognizer应该仅从应用程序的主线程中使用”。对于开发本机android代码的人来说,这不应该是一个大问题,但我实际上使用phonegap来避免原生的Android代码。
答案 0 :(得分:1)
也许这会有所帮助:
线程
插件的JavaScript不在WebView的主线程中运行 接口;相反,它在WebCore线程上运行,执行也是如此 方法。如果您需要与用户界面进行交互,则应该 使用以下变体:
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if ("beep".equals(action)) {
final long duration = args.getLong(0);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
...
callbackContext.success(); // Thread-safe.
}
});
return true;
}
return false;
}
http://docs.phonegap.com/en/3.5.0/guide_platforms_android_plugin.md.html#Android%20Plugins
或其他问题
Android SpeechRecognizer should only be used from the application's main thread
答案 1 :(得分:0)
使用自定义AngularJS指令将语音识别功能添加到HTML按钮: