Java Code Examples for android.media.AudioManager#AUDIOFOCUS_GAIN

The following examples show how to use android.media.AudioManager#AUDIOFOCUS_GAIN . 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: JCVideoPlayer.java    From SprintNBA with Apache License 2.0 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            break;
        case AudioManager.AUDIOFOCUS_LOSS:
            releaseAllVideos();
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                JCMediaManager.instance().mediaPlayer.pause();
            }
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            break;
    }
}
 
Example 2
Source File: JCVideoPlayer.java    From JieCaoVideoPlayer-develop with MIT License 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            break;
        case AudioManager.AUDIOFOCUS_LOSS:
            releaseAllVideos();
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            if (JCMediaManager.instance().mediaPlayer.isPlaying()) {
                JCMediaManager.instance().mediaPlayer.pause();
            }
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            break;
    }
}
 
Example 3
Source File: AudioPlayerService.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
	switch (focusChange) {
		case AudioManager.AUDIOFOCUS_LOSS: {
			pause(true);
			break;
		}
		case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: {
			boolean playing = mediaPlayer.isPlaying();
			pause(false);
			if (playing) {
				pausedByTransientLossOfFocus = true;
			}
			break;
		}
		case AudioManager.AUDIOFOCUS_GAIN: {
			if (pausedByTransientLossOfFocus) {
				play(false);
			}
			break;
		}
	}
}
 
Example 4
Source File: WebPlayerView.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
        if (videoPlayer.isPlaying()) {
            videoPlayer.pause();
            updatePlayButton();
        }
        hasAudioFocus = false;
        audioFocus = AUDIO_NO_FOCUS_NO_DUCK;
    } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        audioFocus = AUDIO_FOCUSED;
        if (resumeAudioOnFocusGain) {
            resumeAudioOnFocusGain = false;
            videoPlayer.play();
        }
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        audioFocus = AUDIO_NO_FOCUS_CAN_DUCK;
    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
        audioFocus = AUDIO_NO_FOCUS_NO_DUCK;
        if (videoPlayer.isPlaying()) {
            resumeAudioOnFocusGain = true;
            videoPlayer.pause();
            updatePlayButton();
        }
    }
}
 
Example 5
Source File: AudioFocusHelper.java    From chromadoze with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_LOSS:
            // For example, a music player or a sleep timer stealing focus.
            NoiseService.stopNow(mContext, R.string.stop_reason_audiofocus);
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            // For example, an alarm or phone call.
            mVolumeListener.setDuckLevel(SampleShuffler.VolumeListener.DuckLevel.SILENT);
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // For example, an email notification.
            mVolumeListener.setDuckLevel(SampleShuffler.VolumeListener.DuckLevel.DUCK);
            break;
        case AudioManager.AUDIOFOCUS_GAIN:
            // Resume the default volume level.
            mVolumeListener.setDuckLevel(SampleShuffler.VolumeListener.DuckLevel.NORMAL);
            break;
    }
}
 
Example 6
Source File: ExoVideoView.java    From v9porn with MIT License 6 votes vote down vote up
/**
 * Requests to obtain the audio focus
 *
 * @return True if the focus was granted
 */
public boolean requestFocus() {
    if (!handleAudioFocus || currentFocus == AudioManager.AUDIOFOCUS_GAIN) {
        return true;
    }

    if (audioManager == null) {
        return false;
    }

    int status = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    if (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == status) {
        currentFocus = AudioManager.AUDIOFOCUS_GAIN;
        return true;
    }

    startRequested = true;
    return false;
}
 
Example 7
Source File: BaseIjkVideoView.java    From youqu_master with Apache License 2.0 5 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    if (currentFocus == focusChange) {
        return;
    }

    currentFocus = focusChange;
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN://获得焦点
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT://暂时获得焦点
            if (startRequested || pausedForLoss) {
                start();
                startRequested = false;
                pausedForLoss = false;
            }
            if (mMediaPlayer != null && !isMute)//恢复音量
                mMediaPlayer.setVolume(1.0f, 1.0f);
            break;
        case AudioManager.AUDIOFOCUS_LOSS://焦点丢失
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://焦点暂时丢失
            if (isPlaying()) {
                pausedForLoss = true;
                pause();
            }
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK://此时需降低音量
            if (mMediaPlayer != null && isPlaying() && !isMute) {
                mMediaPlayer.setVolume(0.1f, 0.1f);
            }
            break;
    }
}
 
Example 8
Source File: PlaybackManager.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Called by AudioManager on audio focus changes.
 * Implementation of {@link AudioManager.OnAudioFocusChangeListener}
 */
@Override
public void onAudioFocusChange(int focusChange) {
    boolean gotFullFocus = false;
    boolean canDuck = false;
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        gotFullFocus = true;

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus. If we can duck (low playback volume), we can keep playing.
        // Otherwise, we need to pause the playback.
        canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
    }

    if (gotFullFocus || canDuck) {
        if (mMediaPlayer != null) {
            if (mPlayOnFocusGain) {
                mPlayOnFocusGain = false;
                mMediaPlayer.start();
                mState = PlaybackState.STATE_PLAYING;
                updatePlaybackState();
            }
            float volume = canDuck ? 0.2f : 1.0f;
            mMediaPlayer.setVolume(volume, volume);
        }
    } else if (mState == PlaybackState.STATE_PLAYING) {
        mMediaPlayer.pause();
        mState = PlaybackState.STATE_PAUSED;
        updatePlaybackState();
    }
}
 
Example 9
Source File: MusicService.java    From SMP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            // resume playback
            if (wasPlaying) {
                start();
                changed = true;
            }
            //player.setVolume(1.0f, 1.0f);
            break;

        case AudioManager.AUDIOFOCUS_LOSS:
            // Lost focus for an unbounded amount of time: stop playback and release media player
            releaseAudio();
            break;

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            // Lost focus for a short time, but we have to stop
            // playback. We don't release the media player because playback
            // is likely to resume

        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            // Lost focus for a short time, but it's ok to keep playing
            // at an attenuated level
            if (getPlayer().isPlaying()) {
                //player.setVolume(0.1f, 0.1f);
                pause();
                wasPlaying = true;
                changed = true;
            }
            else {
                wasPlaying = false;
                stopSensor();
            }
            break;
    }
}
 
Example 10
Source File: LocalMusicPlayService.java    From MusicPlus with Apache License 2.0 5 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
	switch (focusChange) {
    case AudioManager.AUDIOFOCUS_GAIN:
        if (mMediaPlayer == null){
        	return;
        }else if (!mMediaPlayer.isPlaying()) {
        	mMediaPlayer.start();
        }
        mMediaPlayer.setVolume(0.5f, 0.5f);
        break;

    case AudioManager.AUDIOFOCUS_LOSS:
        if (mMediaPlayer.isPlaying()) 
        	mMediaPlayer.stop();
        mMediaPlayer.release();
        break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
        if (mMediaPlayer.isPlaying()) 
        	mMediaPlayer.pause();
        break;

    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
        if (mMediaPlayer.isPlaying()) 
        	mMediaPlayer.setVolume(0.1f, 0.1f);
        break;
	}

}
 
Example 11
Source File: AudioFocusHelper.java    From DKVideoPlayer with Apache License 2.0 5 votes vote down vote up
private void handleAudioFocusChange(int focusChange) {
    final VideoView videoView = mWeakVideoView.get();
    if (videoView == null) {
        return;
    }
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN://获得焦点
        case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT://暂时获得焦点
            if (mStartRequested || mPausedForLoss) {
                videoView.start();
                mStartRequested = false;
                mPausedForLoss = false;
            }
            if (!videoView.isMute())//恢复音量
                videoView.setVolume(1.0f, 1.0f);
            break;
        case AudioManager.AUDIOFOCUS_LOSS://焦点丢失
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://焦点暂时丢失
            if (videoView.isPlaying()) {
                mPausedForLoss = true;
                videoView.pause();
            }
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK://此时需降低音量
            if (videoView.isPlaying() && !videoView.isMute()) {
                videoView.setVolume(0.1f, 0.1f);
            }
            break;
    }
}
 
Example 12
Source File: PlayerAdapter.java    From android-MediaBrowserService with Apache License 2.0 5 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_GAIN:
            if (mPlayOnAudioFocus && !isPlaying()) {
                play();
            } else if (isPlaying()) {
                setVolume(MEDIA_VOLUME_DEFAULT);
            }
            mPlayOnAudioFocus = false;
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
            setVolume(MEDIA_VOLUME_DUCK);
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            if (isPlaying()) {
                mPlayOnAudioFocus = true;
                pause();
            }
            break;
        case AudioManager.AUDIOFOCUS_LOSS:
            mAudioManager.abandonAudioFocus(this);
            mPlayOnAudioFocus = false;
            stop();
            break;
    }
}
 
Example 13
Source File: ReactExoplayerView.java    From react-native-video with MIT License 5 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_LOSS:
            eventEmitter.audioFocusChanged(false);
            pausePlayback();
            audioManager.abandonAudioFocus(this);
            break;
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
            eventEmitter.audioFocusChanged(false);
            break;
        case AudioManager.AUDIOFOCUS_GAIN:
            eventEmitter.audioFocusChanged(true);
            break;
        default:
            break;
    }

    if (player != null) {
        if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
            // Lower the volume
            if (!muted) {
                player.setVolume(audioVolume * 0.8f);
            }
        } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
            // Raise it back to normal
            if (!muted) {
                player.setVolume(audioVolume * 1);
            }
        }
    }
}
 
Example 14
Source File: PlaybackManager.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
/**
 * Called by AudioManager on audio focus changes.
 * Implementation of {@link AudioManager.OnAudioFocusChangeListener}
 */
@Override
public void onAudioFocusChange(int focusChange) {
    boolean gotFullFocus = false;
    boolean canDuck = false;
    if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
        gotFullFocus = true;

    } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
            focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
        // We have lost focus. If we can duck (low playback volume), we can keep playing.
        // Otherwise, we need to pause the playback.
        canDuck = focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK;
    }

    if (gotFullFocus || canDuck) {
        if (mMediaPlayer != null) {
            if (mPlayOnFocusGain) {
                mPlayOnFocusGain = false;
                mMediaPlayer.start();
                mState = PlaybackState.STATE_PLAYING;
                updatePlaybackState();
            }
            float volume = canDuck ? 0.2f : 1.0f;
            mMediaPlayer.setVolume(volume, volume);
        }
    } else if (mState == PlaybackState.STATE_PLAYING) {
        mMediaPlayer.pause();
        mState = PlaybackState.STATE_PAUSED;
        updatePlaybackState();
    }
}
 
Example 15
Source File: MusicPlaybackService.java    From leanback-showcase with Apache License 2.0 5 votes vote down vote up
@Override
public void handleMessage(Message msg) {
    switch (msg.what) {
        case FOCUS_CHANGE:
            switch (msg.arg1)
            {
                case AudioManager.AUDIOFOCUS_LOSS:
                    if (mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener) !=
                            AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        Log.w(TAG, "abandonAudioFocus after AudioFocus_LOSS failed!");
                    }
                    pause();
                    Log.d(TAG, "AudioFocus: Received AUDIOFOCUS_LOSS.");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    Log.d(TAG, "AudioFocus: Received AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK.");
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    Log.d(TAG, "AudioFocus: Received AUDIOFOCUS_LOSS_TRANSIENT.");
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    Log.d(TAG, "AudioFocus: Received AUDIOFOCUS_GAIN.");
                    break;
            }
            break;
    }
}
 
Example 16
Source File: MediaPlaybackService.java    From coursera-android with MIT License 4 votes vote down vote up
@Override
public void handleMessage(Message msg) {
    MusicUtils.debugLog("mMediaplayerHandler.handleMessage " + msg.what);
    switch (msg.what) {
        case FADEDOWN:
            mCurrentVolume -= .05f;
            if (mCurrentVolume > .2f) {
                mMediaplayerHandler.sendEmptyMessageDelayed(FADEDOWN, 10);
            } else {
                mCurrentVolume = .2f;
            }
            mPlayer.setVolume(mCurrentVolume);
            break;
        case FADEUP:
            mCurrentVolume += .01f;
            if (mCurrentVolume < 1.0f) {
                mMediaplayerHandler.sendEmptyMessageDelayed(FADEUP, 10);
            } else {
                mCurrentVolume = 1.0f;
            }
            mPlayer.setVolume(mCurrentVolume);
            break;
        case SERVER_DIED:
            if (mIsSupposedToBePlaying) {
                gotoNext(true);
            } else {
                // the server died when we were idle, so just
                // reopen the same song (it will start again
                // from the beginning though when the user
                // restarts)
                openCurrentAndNext();
            }
            break;
        case TRACK_WENT_TO_NEXT:
            mPlayPos = mNextPlayPos;
            if (mCursor != null) {
                mCursor.close();
                mCursor = null;
            }
            mCursor = getCursorForId(mPlayList[mPlayPos]);
            notifyChange(META_CHANGED);
            updateNotification();
            setNextTrack();
            break;
        case TRACK_ENDED:
            if (mRepeatMode == REPEAT_CURRENT) {
                seek(0);
                play();
            } else {
                gotoNext(false);
            }
            break;
        case RELEASE_WAKELOCK:
            mWakeLock.release();
            break;

        case FOCUSCHANGE:
            // This code is here so we can better synchronize it with the code that
            // handles fade-in
            switch (msg.arg1) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS");
                    if(isPlaying()) {
                        mPausedByTransientLossOfFocus = false;
                    }
                    pause();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    mMediaplayerHandler.removeMessages(FADEUP);
                    mMediaplayerHandler.sendEmptyMessage(FADEDOWN);
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_LOSS_TRANSIENT");
                    if(isPlaying()) {
                        mPausedByTransientLossOfFocus = true;
                    }
                    pause();
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    Log.v(LOGTAG, "AudioFocus: received AUDIOFOCUS_GAIN");
                    if(!isPlaying() && mPausedByTransientLossOfFocus) {
                        mPausedByTransientLossOfFocus = false;
                        mCurrentVolume = 0f;
                        mPlayer.setVolume(mCurrentVolume);
                        play(); // also queues a fade-in
                    } else {
                        mMediaplayerHandler.removeMessages(FADEDOWN);
                        mMediaplayerHandler.sendEmptyMessage(FADEUP);
                    }
                    break;
                default:
                    Log.e(LOGTAG, "Unknown audio focus change code");
            }
            break;

        default:
            break;
    }
}
 
Example 17
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 18
Source File: AudioFocusManager.java    From Telegram with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
  // Convert the platform focus change to internal state.
  switch (focusChange) {
    case AudioManager.AUDIOFOCUS_LOSS:
      audioFocusState = AUDIO_FOCUS_STATE_LOST_FOCUS;
      break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
      audioFocusState = AUDIO_FOCUS_STATE_LOSS_TRANSIENT;
      break;
    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
      if (willPauseWhenDucked()) {
        audioFocusState = AUDIO_FOCUS_STATE_LOSS_TRANSIENT;
      } else {
        audioFocusState = AUDIO_FOCUS_STATE_LOSS_TRANSIENT_DUCK;
      }
      break;
    case AudioManager.AUDIOFOCUS_GAIN:
      audioFocusState = AUDIO_FOCUS_STATE_HAVE_FOCUS;
      break;
    default:
      Log.w(TAG, "Unknown focus change type: " + focusChange);
      // Early return.
      return;
  }

  // Handle the internal state (change).
  switch (audioFocusState) {
    case AUDIO_FOCUS_STATE_NO_FOCUS:
      // Focus was not requested; nothing to do.
      break;
    case AUDIO_FOCUS_STATE_LOST_FOCUS:
      playerControl.executePlayerCommand(PLAYER_COMMAND_DO_NOT_PLAY);
      abandonAudioFocus(/* forceAbandon= */ true);
      break;
    case AUDIO_FOCUS_STATE_LOSS_TRANSIENT:
      playerControl.executePlayerCommand(PLAYER_COMMAND_WAIT_FOR_CALLBACK);
      break;
    case AUDIO_FOCUS_STATE_LOSS_TRANSIENT_DUCK:
      // Volume will be adjusted by the code below.
      break;
    case AUDIO_FOCUS_STATE_HAVE_FOCUS:
      playerControl.executePlayerCommand(PLAYER_COMMAND_PLAY_WHEN_READY);
      break;
    default:
      throw new IllegalStateException("Unknown audio focus state: " + audioFocusState);
  }

  float volumeMultiplier =
      (audioFocusState == AUDIO_FOCUS_STATE_LOSS_TRANSIENT_DUCK)
          ? AudioFocusManager.VOLUME_MULTIPLIER_DUCK
          : AudioFocusManager.VOLUME_MULTIPLIER_DEFAULT;
  if (AudioFocusManager.this.volumeMultiplier != volumeMultiplier) {
    AudioFocusManager.this.volumeMultiplier = volumeMultiplier;
    playerControl.setVolumeMultiplier(volumeMultiplier);
  }
}
 
Example 19
Source File: MusicPlayer.java    From iGap-Android with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    G.onAudioFocusChangeListener = this;

    if (intent == null || intent.getExtras() == null) {
        stopForeground(false);
        stopSelf();
    } else {

        String action = intent.getExtras().getString("ACTION");
        if (action != null) {

            if (action.equals(STARTFOREGROUND_ACTION)) {

                if (notification != null) {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        CharSequence name = G.context.getString(R.string.channel_name_notification);// The user-visible name of the channel.
                        @SuppressLint("WrongConstant") NotificationChannel mChannel = new NotificationChannel(musicChannelId, name, NotificationManager.IMPORTANCE_HIGH);
                        getNotificationManager().createNotificationChannel(mChannel);
                    }

                    try {
                        startForeground(notificationId, notification);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                    if (latestAudioFocusState != AudioManager.AUDIOFOCUS_GAIN) { // if do double "AUDIOFOCUS_GAIN", "AUDIOFOCUS_LOSS" will be called
                        latestAudioFocusState = AudioManager.AUDIOFOCUS_GAIN;
                        registerAudioFocus(AudioManager.AUDIOFOCUS_GAIN);
                    }
                }
                initSensor();
            } else if (action.equals(STOPFOREGROUND_ACTION)) {

                removeSensor();

                stopForeground(false);
                stopSelf();
            }
        }
    }

    return START_STICKY;
}
 
Example 20
Source File: PlayerService.java    From Prodigal with Apache License 2.0 4 votes vote down vote up
@Override
public void onAudioFocusChange(int focusChange) {
    if (focusChange <= 0) {
        if (mediaPlayer.isPlaying())
            mediaPlayer.pause();
    }
    switch (focusChange) {
        case AudioManager.AUDIOFOCUS_LOSS: {
            if(mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
            break;
        }
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: {
            mediaPlayer.pause();
            break;
        }
        case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: {
            if(mediaPlayer != null) {
                mediaPlayer.setVolume(0.3f, 0.3f);
            }
            break;
        }
        case AudioManager.AUDIOFOCUS_GAIN: {
            if(mediaPlayer != null) {
                if( !mediaPlayer.isPlaying() ) {
                    mediaPlayer.start();
                }
                mediaPlayer.setVolume(1.0f, 1.0f);
            }
            break;
        }
        default: {
            if (focusChange <= 0) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                }
            }
            break;
        }
    }
}