2017-08-08 44 views
0

我一直在試圖找到一種方法來實現SpeechRecognizer API在一個服務(在後臺運行),以便當條件滿足時,它將打開語音識別器,而不必在應用。我的問題是,這在本地是否可能?如果是這樣,它將如何完成?在Android服務中觸發語音識別

+0

你到目前爲止做了什麼?在後臺運行SpeechRecognizer並不是一個好主意,因爲它會消耗太多的電池和互聯網等資源。 –

+0

我不會在後臺運行它,它會在條件滿足時觸發。 – sebklopfer

+0

您是否使用自定義偵聽器而不是Google Prompt知道SpeechRecognizer? –

回答

1

這是我的代碼片段。您可以在服務中使用這種識別偵聽器。 我不知道你是如何安排你的服務,我已經把它留給你了。但你可以做這樣的事情。 (我沒有添加代碼重新啓動服務/啓動它在計時器等)

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) { 

     } 
    } 

    } 
+0

太棒了!感謝堆 – sebklopfer

+0

沒有probs。乾杯! – Pavan