大家好!我正在开发一个语音识别应用程序,该应用程序现在能够识别语音!但是,我需要在应用程序的后台运行此语音识别代码,它必须始终监听命令。对于我的应用程序,我编写了 Handler().postDelayed 函数,它计算用户登陆新 Activity 的时间,并通过延迟 5 秒开始监听。我的问题是它只听了2-3秒,并且无法识别和再次聆听。如何在应用运行时在应用后台运行语音识别?
speechRecognizer1.setRecognitionListener(new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle bundle) {
ArrayList<String> matches1 =bundle.getStringArrayList(speechRecognizer1.RESULTS_RECOGNITION);
String string="";
if(matches1!=null) {
string = matches1.get(0);
textView3.setText(string);
Speak();
}
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
});
mTTS1 = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
int result= mTTS1.setLanguage(Locale.ENGLISH);
if(result== TextToSpeech.LANG_MISSING_DATA || result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS","Language Not Supported");
}
}
}
});
new Handler().postDelayed(new Runnable(){
public void run(){
speechRecognizer1.startListening(intentRecognizer1);
}
}, 5000);
最佳答案
好的,为此你需要一个名为 Service 的 Android 组件 我们在 android 中提供三种类型的服务: 1.前台: 前台服务所做的工作对用户来说是引人注目的,例如带有有关正在播放的歌曲的通知的音乐应用程序。 2.背景: 用户不会注意到该服务 3.绑定(bind): 以及为用户提供客户端-服务器交互的绑定(bind)服务
对于您的情况,您可以使用前台服务。 要决定什么更好以及如何实现它或在线程和服务之间做出决定,我建议阅读此文档: https://developer.android.com/guide/components/services
关于java - 如何在应用程序后台运行RecognitionListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62176066/