3

我制作了一个音频播放器,当用户启动谷歌语音搜索时我需要暂停它。

我只是尝试了两种方法,但都失败了

  1. 编写一个接收器来接收广播动作意图“android.speech.action.RECOGNIZE_SPEECH”,但它根本不起作用,无法接收来自语音搜索的回调。

  2. 编写一个服务来获取 SpeechRecognizer,如下,(我的部分代码)

代码:

  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);
      }
   }

只是在我启动语音搜索后无法收到回调onReadyForSpeech“onEndOfSpeech”,所以我无法暂停我的音频。我只是想知道是否有办法获取谷歌语音搜索的 SpeechRecognizer 实例,以便我可以正确获取回调?

有人知道我的问题的答案吗?谢谢帮忙!!!

喜悦

4

1 回答 1

1

我最初为这个问题采取了相同的路线,但解决方案是使用 AudioManager 而不是 SpeechRecognizer。

我们的应用程序已经在为 AudioManager.OnAudioFocusChangeListener 使用自定义侦听器,并且正确响应了 AUDIOFOCUS_GAIN 和 AUDIOFOCUS_LOSS 状态。事实证明,语音搜索触发了 AUDIOFOCUS_LOSS_TRANSIENT 状态,因此将其添加到更改侦听器会导致在执行语音搜索时暂停播放。

总结一下:

创建监听器

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();
    }
};

获取AudioManager,请求焦点,传递监听器

AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(audioFocusListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
于 2012-02-13T22:00:29.677 回答