I made an Audio-Player and I need to pause it when the user launches google Voice Search.
I just tried 2 ways, but all failed
Write an receiver to receive broadcast action intent "android.speech.action.RECOGNIZE_SPEECH", but it doesn't work at all, can not receive callback from Voice Search.
W开发者_StackOverflowrite a service to get SpeechRecognizer, as following, (partial of my codes)
code:
public class VoiceSearchMonitor extends Service
{
@Override
public IBinder onBind(Intent intent)
{
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate()
{
// Get SpeechRecognizer
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(context);
// Create a new RecognitionListener
RecognitionListener listener = new RecognitionListener()
{
@Override
public void onReadyForSpeech(Bundle params)
{
// *** I want to pause my audio here ***
}
@Override
public void onEndOfSpeech()
{
// *** I want to resume my audio here ***
}
}
// make an intent
Intent intent = new Intent("android.speech.action.RECOGNIZE_SPEECH");
// Start listening
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
}
}
Just can not receive the callback onReadyForSpeech
, 'onEndOfSpeech' after I launch Voice Search, so there's no way for me to pause my audio. I just wonder if there is a way to get SpeechRecognizer instance of google's Voice Search, so that I can get the callback correctly??
Does anyone know the answer to my question? Thanks for helping!!!
Joy
I took the same route initially for this issue, but the solution is to use the AudioManager rather than the SpeechRecognizer.
Our app was already using a custom listener for AudioManager.OnAudioFocusChangeListener and was correctly responding to the AUDIOFOCUS_GAIN and AUDIOFOCUS_LOSS states. It turns out that the voice search triggers an AUDIOFOCUS_LOSS_TRANSIENT state, so adding that to the change listener resulted in playback being paused while the voice search was performed.
To summarize:
Create the listener
AudioManager.OnAudioFocusChangeListener audioFocusListener =
new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
Logging.d(TAG, "audiofocus change");
if(focusChange == AudioManager.AUDIOFOCUS_LOSS || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)
suspendPlayback();
if(focusChange == AudioManager.AUDIOFOCUS_GAIN)
resumePlayback();
}
};
Get the AudioManager, request focus, and pass the listener
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
精彩评论