2017-08-05 168 views
4

我試圖跟蹤SpeechRecognizer狀態,這樣的:如何檢查SpeechRecognizer當前是否正在運行?

private SpeechRecognizer mInternalSpeechRecognizer; 
private boolean mIsRecording; 

public void startRecording(Intent intent) { 
mIsRecording = true; 
// ... 
mInternalSpeechRecognizer.startListening(intent); 
} 

問題與方法是保持mIsRecording標誌最新的是艱難的,例如如果有ERROR_NO_MATCH錯誤,應該將其設置爲false或者不是?
我在印象之下有些設備停止錄音然後和其他人沒有。

我沒有看到像SpeechRecognizer.isRecording(context)這樣的方法,所以我想知道是否有方法通過運行服務進行查詢。

回答

0

處理結束或錯誤情況的一種解決方案是將RecognitionListener設置爲SpeechRecognizer實例。你必須這樣做之前致電startListening()

例子:

mInternalSpeechRecognizer.setRecognitionListener(new RecognitionListener() { 

    // Other methods implementation 

    @Override 
    public void onEndOfSpeech() { 
     // Handle end of speech recognition 
    } 

    @Override 
    public void onError(int error) { 
     // Handle end of speech recognition and error 
    } 

    // Other methods implementation 
}); 

在你的情況,你可以讓你的類包含mIsRecording屬性實現RecognitionListener接口。然後,你就必須重寫這兩種方法有以下指令:

mIsRecording = false; 

此外,你mIsRecording = true指令是在錯誤的地方。您應該在onReadyForSpeech(Bundle params)方法定義中執行此操作,否則,在此值爲true時語音識別可能永遠不會啓動。

最後,在類管理它,中庸之道創建如下方法:

// Other RecognitionListener's methods implementation 

@Override 
public void onEndOfSpeech() { 
    mIsRecording = false; 
} 

@Override 
public void onError(int error) { 
    mIsRecording = false; 
    // Print error 
} 

@Override 
void onReadyForSpeech (Bundle params) { 
    mIsRecording = true; 
} 

public void startRecording(Intent intent) { 
    // ... 
    mInternalSpeechRecognizer.setRecognitionListener(this); 
    mInternalSpeechRecognizer.startListening(intent); 
} 

public boolean recordingIsRunning() { 
    return mIsRecording; 
} 

注意有關recordingIsRunning調用線程安全的,一切都會好起來:)

+0

正如我在一個問題中提到,如果'onError'正在執行,那麼* not *表示設備停止錄製音頻。如果是ERROR_NO_MATCH,有時會停止錄製,有時不會。 – Piotr

+0

如果你在'ERROR_NO_MATCH'的情況下調用'stopListening()'會怎麼樣? – N0un

+0

但是如果設備想繼續播放,我不想停止錄製。 – Piotr

相關問題