Java Code Examples for android.media.AudioManager#OnAudioFocusChangeListener

The following examples show how to use android.media.AudioManager#OnAudioFocusChangeListener . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiSampleVideo.java    From GSYVideoPlayer with Apache License 2.0 6 votes vote down vote up
@Override
protected void init(Context context) {
    super.init(context);
    mCoverImage = (ImageView) findViewById(R.id.thumbImage);
    if (mThumbImageViewLayout != null &&
            (mCurrentState == -1 || mCurrentState == CURRENT_STATE_NORMAL || mCurrentState == CURRENT_STATE_ERROR)) {
        mThumbImageViewLayout.setVisibility(VISIBLE);
    }
    onAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    //todo 判断如果不是外界造成的就不处理
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    //todo 判断如果不是外界造成的就不处理
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    break;
            }
        }
    };
}
 
Example 2
Source File: AudioManagerUtils.java    From DevUtils with Apache License 2.0 5 votes vote down vote up
/**
 * 放弃音频焦点, 使上一个焦点所有者 ( 如果有 ) 接收焦点
 * @param listener 焦点监听事件
 * @return {@code true} success, {@code false} fail
 */
public static boolean abandonAudioFocus(final AudioManager.OnAudioFocusChangeListener listener) {
    AudioManager audioManager = AppUtils.getAudioManager();
    if (audioManager != null) {
        try {
            audioManager.abandonAudioFocus(listener);
            return true;
        } catch (Exception e) {
            LogPrintUtils.eTag(TAG, e, "abandonAudioFocus");
        }
    }
    return false;
}
 
Example 3
Source File: AudioFocusManager.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
/* package */ AudioManager.OnAudioFocusChangeListener getFocusListener() {
  return focusListener;
}
 
Example 4
Source File: AppRTCAudioManager.java    From imsdk-android with MIT License 4 votes vote down vote up
public void start(AudioManagerEvents audioManagerEvents) {
  LogUtil.d(TAG, "start");
  AppRTCUtils.checkIsOnMainThread(apprtcContext);
  if (amState == AudioManagerState.RUNNING) {
    LogUtil.e(TAG, "AudioManager is already active");
    return;
  }
  amState = AudioManagerState.RUNNING;

  // TODO(henrika): perhaps call new method called preInitAudio() here if UNINITIALIZED.

  LogUtil.d(TAG, "AudioManager starts...");
  this.audioManagerEvents = audioManagerEvents;

  // Store current audio state so we can restore it when stop() is called.
  savedAudioMode = audioManager.getMode();
  savedIsSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
  savedIsMicrophoneMute = audioManager.isMicrophoneMute();
  hasWiredHeadset = hasWiredHeadset();

  // Create an AudioManager.OnAudioFocusChangeListener instance.
  audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
    // Called on the listener to notify if the audio focus for this listener has been changed.
    // The |focusChange| value indicates whether the focus was gained, whether the focus was lost,
    // and whether that loss is transient, or whether the new focus holder will hold it for an
    // unknown amount of time.
    // TODO(henrika): possibly extend support of handling audio-focus changes. Only contains
    // logging for now.
    @Override
    public void onAudioFocusChange(int focusChange) {
      String typeOfChange = "AUDIOFOCUS_NOT_DEFINED";
      switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
          typeOfChange = "AUDIOFOCUS_GAIN";
          break;
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
          typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT";
          break;
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
          typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE";
          break;
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
          typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK";
          break;
        case AudioManager.AUDIOFOCUS_LOSS:
          typeOfChange = "AUDIOFOCUS_LOSS";
          break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
          typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT";
          break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
          typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK";
          break;
        default:
          typeOfChange = "AUDIOFOCUS_INVALID";
          break;
      }
      LogUtil.d(TAG, "onAudioFocusChange: " + typeOfChange);
    }
  };

  // Request audio playout focus (without ducking) and install listener for changes in focus.
  int result = audioManager.requestAudioFocus(audioFocusChangeListener,
      AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
  if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    LogUtil.d(TAG, "Audio focus request granted for VOICE_CALL streams");
  } else {
    LogUtil.e(TAG, "Audio focus request failed");
  }

  // Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
  // required to be in this mode when playout and/or recording starts for
  // best possible VoIP performance.
  audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

  // Always disable microphone mute during a WebRTC call.
  setMicrophoneMute(false);

  // Set initial device states.
  userSelectedAudioDevice = AudioDevice.NONE;
  selectedAudioDevice = AudioDevice.NONE;
  audioDevices.clear();

  // Initialize and start Bluetooth if a BT device is available or initiate
  // detection of new (enabled) BT devices.
  bluetoothManager.start();

  // Do initial selection of audio device. This setting can later be changed
  // either by adding/removing a BT or wired headset or by covering/uncovering
  // the proximity sensor.
  updateAudioDeviceState();

  // Register receiver for broadcast intents related to adding/removing a
  // wired headset.
  registerReceiver(wiredHeadsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
  LogUtil.d(TAG, "AudioManager started");
}
 
Example 5
Source File: AppRTCAudioManager.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public void start(AudioManagerEvents audioManagerEvents) {
    Log.d(Config.LOGTAG, AppRTCAudioManager.class.getName() + ".start()");
    ThreadUtils.checkIsOnMainThread();
    if (amState == AudioManagerState.RUNNING) {
        Log.e(Config.LOGTAG, "AudioManager is already active");
        return;
    }
    awaitMicrophoneLatch();
    this.audioManagerEvents = audioManagerEvents;
    amState = AudioManagerState.RUNNING;
    // Store current audio state so we can restore it when stop() is called.
    savedIsSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
    savedIsMicrophoneMute = audioManager.isMicrophoneMute();
    hasWiredHeadset = hasWiredHeadset();
    // Create an AudioManager.OnAudioFocusChangeListener instance.
    audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        // Called on the listener to notify if the audio focus for this listener has been changed.
        // The |focusChange| value indicates whether the focus was gained, whether the focus was lost,
        // and whether that loss is transient, or whether the new focus holder will hold it for an
        // unknown amount of time.
        // TODO(henrika): possibly extend support of handling audio-focus changes. Only contains
        // logging for now.
        @Override
        public void onAudioFocusChange(int focusChange) {
            final String typeOfChange;
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    typeOfChange = "AUDIOFOCUS_GAIN";
                    break;
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                    typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT";
                    break;
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
                    typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE";
                    break;
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                    typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK";
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    typeOfChange = "AUDIOFOCUS_LOSS";
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT";
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK";
                    break;
                default:
                    typeOfChange = "AUDIOFOCUS_INVALID";
                    break;
            }
            Log.d(Config.LOGTAG, "onAudioFocusChange: " + typeOfChange);
        }
    };
    // Request audio playout focus (without ducking) and install listener for changes in focus.
    int result = audioManager.requestAudioFocus(audioFocusChangeListener,
            AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d(Config.LOGTAG, "Audio focus request granted for VOICE_CALL streams");
    } else {
        Log.e(Config.LOGTAG, "Audio focus request failed");
    }
    // Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
    // required to be in this mode when playout and/or recording starts for
    // best possible VoIP performance.
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    // Always disable microphone mute during a WebRTC call.
    setMicrophoneMute(false);
    // Set initial device states.
    userSelectedAudioDevice = AudioDevice.NONE;
    selectedAudioDevice = AudioDevice.NONE;
    audioDevices.clear();
    // Initialize and start Bluetooth if a BT device is available or initiate
    // detection of new (enabled) BT devices.
    bluetoothManager.start();
    // Do initial selection of audio device. This setting can later be changed
    // either by adding/removing a BT or wired headset or by covering/uncovering
    // the proximity sensor.
    updateAudioDeviceState();
    // Register receiver for broadcast intents related to adding/removing a
    // wired headset.
    registerReceiver(wiredHeadsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    Log.d(Config.LOGTAG, "AudioManager started");
}
 
Example 6
Source File: MainService.java    From android-play-games-in-motion with Apache License 2.0 4 votes vote down vote up
@Override
public void onCreate() {
    // The service is being created.
    Utils.logDebug(TAG, "onCreate");
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_1);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_2);
    intentFilter.addAction(CHOICE_NOTIFICATION_ACTION_3);
    registerReceiver(mReceiver, intentFilter);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    // Determines the behavior for handling Audio Focus surrender.
    mAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
                    || focusChange == AudioManager.AUDIOFOCUS_LOSS) {

                if (mTextToSpeech.isSpeaking()) {
                    mTextToSpeech.setOnUtteranceProgressListener(null);
                    mTextToSpeech.stop();
                }

                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.stop();
                }

                // Abandon Audio Focus, if it's requested elsewhere.
                mAudioManager.abandonAudioFocus(mAudioFocusChangeListener);

                // Restart the current moment if AudioFocus was lost. Since AudioFocus is only
                // requested away from this application if this application was using it,
                // only Moments that play sound will restart in this way.
                if (mMission != null) {
                    mMission.restartMoment();
                }
            }
        }
    };

    // Asynchronously prepares the TextToSpeech.
    mTextToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                // Check if language is available.
                switch (mTextToSpeech.isLanguageAvailable(DEFAULT_TEXT_TO_SPEECH_LOCALE)) {
                    case TextToSpeech.LANG_AVAILABLE:
                    case TextToSpeech.LANG_COUNTRY_AVAILABLE:
                    case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
                        Utils.logDebug(TAG, "TTS locale supported.");
                        mTextToSpeech.setLanguage(DEFAULT_TEXT_TO_SPEECH_LOCALE);
                        mIsTextToSpeechReady = true;
                        break;
                    case TextToSpeech.LANG_MISSING_DATA:
                        Utils.logDebug(TAG, "TTS missing data, ask for install.");
                        Intent installIntent = new Intent();
                        installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                        startActivity(installIntent);
                        break;
                    default:
                        Utils.logDebug(TAG, "TTS local not supported.");
                        break;
                }
            }
        }
    });

    mMediaPlayer = new MediaPlayer();
}
 
Example 7
Source File: AudioFocusManager.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
@VisibleForTesting
/* package */ AudioManager.OnAudioFocusChangeListener getFocusListener() {
  return focusListener;
}
 
Example 8
Source File: AppRTCAudioManager.java    From Conversations with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public void start(AudioManagerEvents audioManagerEvents) {
    Log.d(Config.LOGTAG, AppRTCAudioManager.class.getName() + ".start()");
    ThreadUtils.checkIsOnMainThread();
    if (amState == AudioManagerState.RUNNING) {
        Log.e(Config.LOGTAG, "AudioManager is already active");
        return;
    }
    awaitMicrophoneLatch();
    this.audioManagerEvents = audioManagerEvents;
    amState = AudioManagerState.RUNNING;
    // Store current audio state so we can restore it when stop() is called.
    savedIsSpeakerPhoneOn = audioManager.isSpeakerphoneOn();
    savedIsMicrophoneMute = audioManager.isMicrophoneMute();
    hasWiredHeadset = hasWiredHeadset();
    // Create an AudioManager.OnAudioFocusChangeListener instance.
    audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
        // Called on the listener to notify if the audio focus for this listener has been changed.
        // The |focusChange| value indicates whether the focus was gained, whether the focus was lost,
        // and whether that loss is transient, or whether the new focus holder will hold it for an
        // unknown amount of time.
        // TODO(henrika): possibly extend support of handling audio-focus changes. Only contains
        // logging for now.
        @Override
        public void onAudioFocusChange(int focusChange) {
            final String typeOfChange;
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_GAIN:
                    typeOfChange = "AUDIOFOCUS_GAIN";
                    break;
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                    typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT";
                    break;
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE:
                    typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_EXCLUSIVE";
                    break;
                case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                    typeOfChange = "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK";
                    break;
                case AudioManager.AUDIOFOCUS_LOSS:
                    typeOfChange = "AUDIOFOCUS_LOSS";
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT";
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    typeOfChange = "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK";
                    break;
                default:
                    typeOfChange = "AUDIOFOCUS_INVALID";
                    break;
            }
            Log.d(Config.LOGTAG, "onAudioFocusChange: " + typeOfChange);
        }
    };
    // Request audio playout focus (without ducking) and install listener for changes in focus.
    int result = audioManager.requestAudioFocus(audioFocusChangeListener,
            AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.d(Config.LOGTAG, "Audio focus request granted for VOICE_CALL streams");
    } else {
        Log.e(Config.LOGTAG, "Audio focus request failed");
    }
    // Start by setting MODE_IN_COMMUNICATION as default audio mode. It is
    // required to be in this mode when playout and/or recording starts for
    // best possible VoIP performance.
    audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    // Always disable microphone mute during a WebRTC call.
    setMicrophoneMute(false);
    // Set initial device states.
    userSelectedAudioDevice = AudioDevice.NONE;
    selectedAudioDevice = AudioDevice.NONE;
    audioDevices.clear();
    // Initialize and start Bluetooth if a BT device is available or initiate
    // detection of new (enabled) BT devices.
    bluetoothManager.start();
    // Do initial selection of audio device. This setting can later be changed
    // either by adding/removing a BT or wired headset or by covering/uncovering
    // the proximity sensor.
    updateAudioDeviceState();
    // Register receiver for broadcast intents related to adding/removing a
    // wired headset.
    registerReceiver(wiredHeadsetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    Log.d(Config.LOGTAG, "AudioManager started");
}
 
Example 9
Source File: AudioFocusManager.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
@VisibleForTesting
/* package */ AudioManager.OnAudioFocusChangeListener getFocusListener() {
  return focusListener;
}