android.media.AudioManager.OnAudioFocusChangeListener Java Examples

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: AudioManagerCompat.java    From Jockey with Apache License 2.0 7 votes vote down vote up
public boolean requestAudioFocus(OnAudioFocusChangeListener focusChangeListener,
                                 int streamType, int audioFocusGain) {
    int r;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        r = mAudioManager.requestAudioFocus(
                new AudioFocusRequest.Builder(audioFocusGain)
                        .setAudioAttributes(
                                new AudioAttributes.Builder()
                                        .setLegacyStreamType(streamType)
                                        .build())
                        .setOnAudioFocusChangeListener(focusChangeListener)
                        .build());
    } else {
        //noinspection deprecation
        r = mAudioManager.requestAudioFocus(focusChangeListener, streamType, audioFocusGain);
    }

    return r == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
 
Example #2
Source File: AudioFocusHelper.java    From carstream-android-auto with Apache License 2.0 6 votes vote down vote up
@Override
public boolean requestAudioFocus(AudioFocusRequestCompat audioFocusRequestCompat) {
    // Save the focus request.
    mAudioFocusRequestCompat = audioFocusRequestCompat;

    // Check for possible problems...
    if (audioFocusRequestCompat.acceptsDelayedFocusGain()) {
        final String message = "Cannot request delayed focus on API " +
                Build.VERSION.SDK_INT;

        // Make an exception to allow the developer to more easily find this code path.
        @SuppressWarnings("ThrowableNotThrown")
        final Throwable stackTrace = new UnsupportedOperationException(message)
                .fillInStackTrace();
        Log.w(TAG, "Cannot request delayed focus", stackTrace);
    }

    final OnAudioFocusChangeListener listener =
            mAudioFocusRequestCompat.getOnAudioFocusChangeListener();
    final int streamType =
            mAudioFocusRequestCompat.getAudioAttributesCompat().getLegacyStreamType();
    final int focusGain = mAudioFocusRequestCompat.getFocusGain();

    return mAudioManager.requestAudioFocus(listener, streamType, focusGain) ==
            AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
 
Example #3
Source File: TwoDScrollerListview.java    From 2DScroller with Apache License 2.0 6 votes vote down vote up
/**
 * To play sound.
 * 
 * @param context
 * 					{@link Context}
 * 
 * @param soundID
 * 					sound id.
 * 	
 * @param soundPool
 * 					{@link SoundPool} instance.
 * 
 */
public void playSound(Context context, int soundID, SoundPool soundPool){
	OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
		public void onAudioFocusChange(int focusChange) {
			if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
				// Lower the volume
			} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
				// Raise it back to normal
			}
		}
	};
	AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);

	// Request audio focus for playback
	int result = audioManager.requestAudioFocus(afChangeListener,
			// Use the music stream.
			AudioManager.STREAM_MUSIC,
			// Request permanent focus.
			AudioManager.AUDIOFOCUS_GAIN);

	if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
		// Start playback.
		soundPool.play(soundID, 10, 10, 1, 0,1f );
	}
}
 
Example #4
Source File: AudioFocusRequestCompat.java    From carstream-android-auto with Apache License 2.0 5 votes vote down vote up
private AudioFocusRequestCompat(int focusGain,
                                OnAudioFocusChangeListener onAudioFocusChangeListener,
                                Handler focusChangeHandler,
                                AudioAttributesCompat audioFocusRequestCompat,
                                boolean pauseOnDuck,
                                boolean acceptsDelayedFocusGain) {
    mFocusGain = focusGain;
    mOnAudioFocusChangeListener = onAudioFocusChangeListener;
    mFocusChangeHandler = focusChangeHandler;
    mAudioAttributesCompat = audioFocusRequestCompat;
    mPauseOnDuck = pauseOnDuck;
    mAcceptsDelayedFocusGain = acceptsDelayedFocusGain;
}
 
Example #5
Source File: AudioFocusRequestCompat.java    From carstream-android-auto with Apache License 2.0 5 votes vote down vote up
@NonNull
public Builder setOnAudioFocusChangeListener(@NonNull OnAudioFocusChangeListener listener,
                                             @NonNull Handler handler) {
    mOnAudioFocusChangeListener = listener;
    mFocusChangeHandler = handler;
    return this;
}
 
Example #6
Source File: AudioPauser.java    From AlexaAndroid with GNU General Public License v2.0 5 votes vote down vote up
public AudioPauser(Context context, boolean isMuteStream) {
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mIsMuteStream = isMuteStream;

    mAfChangeListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            Log.i("onAudioFocusChange" + focusChange);
        }
    };
}
 
Example #7
Source File: AudioPauser.java    From AlexaAndroid with GNU General Public License v2.0 5 votes vote down vote up
public AudioPauser(Context context, boolean isMuteStream) {
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    mIsMuteStream = isMuteStream;

    mAfChangeListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            Log.i("onAudioFocusChange" + focusChange);
        }
    };
}
 
Example #8
Source File: AudioManagerCompat.java    From Jockey with Apache License 2.0 5 votes vote down vote up
public void abandonAudioFocus(OnAudioFocusChangeListener focusChangeListener) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        mAudioManager.abandonAudioFocusRequest(
                new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                        .setOnAudioFocusChangeListener(focusChangeListener)
                        .build());
    } else {
        //noinspection deprecation
        mAudioManager.abandonAudioFocus(focusChangeListener);
    }
}
 
Example #9
Source File: AudioFocusRequestCompat.java    From carstream-android-auto with Apache License 2.0 4 votes vote down vote up
OnAudioFocusChangeListener getOnAudioFocusChangeListener() {
    return mOnAudioFocusChangeListener;
}
 
Example #10
Source File: AudioFocusRequestCompat.java    From carstream-android-auto with Apache License 2.0 4 votes vote down vote up
@NonNull
public Builder setOnAudioFocusChangeListener(@NonNull OnAudioFocusChangeListener listener) {
    return setOnAudioFocusChangeListener(listener, new Handler(Looper.getMainLooper()));
}
 
Example #11
Source File: Util.java    From Audinaut with GNU General Public License v3.0 4 votes vote down vote up
public static void requestAudioFocus(final Context context) {
    if (focusListener == null) {
        final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.requestAudioFocus(focusListener = new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                DownloadService downloadService = (DownloadService) context;
                switch (focusChange) {
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        if (downloadService.getPlayerState() == PlayerState.STARTED) {
                            Log.i(TAG, "Temporary loss of focus");
                            SharedPreferences prefs = getPreferences(context);
                            int lossPref = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
                            if (lossPref == 2 || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
                                lowerFocus = true;
                                downloadService.setVolume(0.1f);
                            } else if (lossPref == 0 || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
                                pauseFocus = true;
                                downloadService.pause(true);
                            }
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN:
                        if (pauseFocus) {
                            pauseFocus = false;
                            downloadService.start();
                        }
                        if (lowerFocus) {
                            lowerFocus = false;
                            downloadService.setVolume(1.0f);
                        }
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        Log.i(TAG, "Permanently lost focus");
                        focusListener = null;
                        downloadService.pause();
                        audioManager.abandonAudioFocus(this);
                        break;
                }
            }
        }, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
}
 
Example #12
Source File: PlaybackService.java    From VCL-Android with Apache License 2.0 4 votes vote down vote up
@TargetApi(Build.VERSION_CODES.FROYO)
private OnAudioFocusChangeListener createOnAudioFocusChangeListener() {
    return new OnAudioFocusChangeListener() {
        private boolean mLossTransient = false;
        private boolean mLossTransientCanDuck = false;

        @Override
        public void onAudioFocusChange(int focusChange) {
            /*
             * Pause playback during alerts and notifications
             */
            switch (focusChange) {
                case AudioManager.AUDIOFOCUS_LOSS:
                    Log.i(TAG, "AUDIOFOCUS_LOSS");
                    // Stop playback
                    changeAudioFocus(false);
                    stop();
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                    Log.i(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
                    // Pause playback
                    if (mMediaPlayer.isPlaying()) {
                        mLossTransient = true;
                        mMediaPlayer.pause();
                    }
                    break;
                case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                    Log.i(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                    // Lower the volume
                    if (mMediaPlayer.isPlaying()) {
                        mMediaPlayer.setVolume(36);
                        mLossTransientCanDuck = true;
                    }
                    break;
                case AudioManager.AUDIOFOCUS_GAIN:
                    Log.i(TAG, "AUDIOFOCUS_GAIN: " + mLossTransientCanDuck + ", " + mLossTransient);
                    // Resume playback
                    if (mLossTransientCanDuck) {
                        mMediaPlayer.setVolume(100);
                        mLossTransientCanDuck = false;
                    }
                    if (mLossTransient) {
                        mMediaPlayer.play();
                        mLossTransient = false;
                    }
                    break;
            }
        }
    };
}
 
Example #13
Source File: Util.java    From Popeens-DSub with GNU General Public License v3.0 4 votes vote down vote up
private static OnAudioFocusChangeListener getAudioFocusChangeListener(final Context context, final AudioManager audioManager) {
	return new OnAudioFocusChangeListener() {
		public void onAudioFocusChange(int focusChange) {
			DownloadService downloadService = (DownloadService)context;
			if((focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) && !downloadService.isRemoteEnabled()) {
				if(downloadService.getPlayerState() == PlayerState.STARTED) {
					Log.i(TAG, "Temporary loss of focus");
					SharedPreferences prefs = getPreferences(context);
					int lossPref = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_TEMP_LOSS, "1"));
					if(lossPref == 2 || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK)) {
						lowerFocus = true;
						downloadService.setVolume(0.1f);
					} else if(lossPref == 0 || (lossPref == 1 && focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT)) {
						pauseFocus = true;
						downloadService.pause(true);
					}
				}
			} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
				if(pauseFocus) {
					pauseFocus = false;
					downloadService.start();
				}
				if(lowerFocus) {
					lowerFocus = false;
					downloadService.setVolume(1.0f);
				}
			} else if(focusChange == AudioManager.AUDIOFOCUS_LOSS && !downloadService.isRemoteEnabled()) {
				Log.i(TAG, "Permanently lost focus");
				focusListener = null;
				downloadService.pause();

				if(audioFocusRequest != null && Build.VERSION.SDK_INT >= 26) {
					audioManager.abandonAudioFocusRequest(audioFocusRequest);
					audioFocusRequest = null;
				} else {
					audioManager.abandonAudioFocus(this);
				}
			}
		}
	};
}
 
Example #14
Source File: AudioFocusHelper.java    From carstream-android-auto with Apache License 2.0 3 votes vote down vote up
/**
 * Builds an {@link OnAudioFocusChangeListener} to control an
 * {@link AudioFocusAwarePlayer} in response to audio focus changes.
 * <p>
 * This function is intended to be used in conjuction with an {@link AudioFocusRequestCompat}
 * as follows:
 * <code>
 * AudioFocusRequestCompat focusRequest =
 *     new AudioFocusRequestCompat.Builder(AudioManager.AUDIOFOCUS_GAIN)
 *         .setOnAudioFocusChangeListener(audioFocusHelper.getListenerForPlayer(player))
 *         // etc...
 *         .build();
 * </code>
 *
 * @param player The player that will respond to audio focus changes.
 * @return An {@link OnAudioFocusChangeListener} to control the player.
 */
public OnAudioFocusChangeListener getListenerForPlayer(@NonNull AudioFocusAwarePlayer player) {
    if (mDefaultChangeListener != null && mDefaultChangeListener.getPlayer().equals(player)) {
        return mDefaultChangeListener;
    }
    mDefaultChangeListener = new DefaultAudioFocusListener(mImpl, player);
    return mDefaultChangeListener;
}