在安卓服务中触发语音识别



我一直在尝试找到一种方法在服务(在后台运行(中实现语音识别器 API,以便在满足条件时,它将打开语音识别器,而不必在应用程序中。我的问题是这在原生上是否可能?如果是这样,它将如何完成?

这是我的代码片段。可以在服务中使用这样的识别侦听器。 我不确定您如何安排服务,我已将其留给您。但是你可以做这样的事情。(我没有添加用于重新启动服务/在计时器中启动服务等的代码(

public class MyService extends Service {
protected static SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
Context c;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if condition is met then do this
SpeechRecognitionListener h = new SpeechRecognitionListener();
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(h);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
Log.d("avail", " " + mSpeechRecognizer.isRecognitionAvailable(this));
if (mSpeechRecognizer.isRecognitionAvailable(this))
Log.d("created", "onBeginingOfSpeech");
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
return START_STICKY;
}

@Override
public void onCreate() {
super.onCreate();
c= getApplicationContext();

}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

class SpeechRecognitionListener implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle bundle) {
Log.d("onReady", "service");
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float v) {
}
@Override
public void onBufferReceived(byte[] bytes) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int i) {
Log.d("ERROR","ERROR");
}
@Override
public void onResults(Bundle resultsBundle) {
Log.d("Results", "onResults"); 
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int i, Bundle bundle) {
}
}
}

相关内容

  • 没有找到相关文章

最新更新