Java Code Examples for android.media.AudioManager#AUDIOFOCUS_REQUEST_GRANTED

The following examples show how to use android.media.AudioManager#AUDIOFOCUS_REQUEST_GRANTED . 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: AudioPauser.java    From speechutils with Apache License 2.0 6 votes vote down vote up
/**
 * Requests audio focus with the goal of pausing any existing audio player.
 * Additionally mutes the music stream, since some audio players might
 * ignore the focus request.
 * In other words, during the pause no sound will be heard,
 * but whether the audio resumes from the same position after the pause
 * depends on the audio player.
 */
public void pause() {
    if (!isPausing) {
        int result = mAudioManager.requestAudioFocus(mAfChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            Log.i("AUDIOFOCUS_REQUEST_GRANTED");
        }

        if (mIsMuteStream) {
            mCurrentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mCurrentVolume > 0) {
                mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            }
        }
        isPausing = true;
    }
}
 
Example 2
Source File: MediaController.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private void checkAudioFocus(MessageObject messageObject) {
    int neededAudioFocus;
    if (messageObject.isVoice() || messageObject.isRoundVideo()) {
        if (useFrontSpeaker) {
            neededAudioFocus = 3;
        } else {
            neededAudioFocus = 2;
        }
    } else {
        neededAudioFocus = 1;
    }
    if (hasAudioFocus != neededAudioFocus) {
        hasAudioFocus = neededAudioFocus;
        int result;
        if (neededAudioFocus == 3) {
            result = NotificationsController.audioManager.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);
        } else {
            result = NotificationsController.audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, neededAudioFocus == 2 ? AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK : AudioManager.AUDIOFOCUS_GAIN);
        }
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            audioFocus = AUDIO_FOCUSED;
        }
    }
}
 
Example 3
Source File: VideoUnit.java    From Dashchan with Apache License 2.0 6 votes vote down vote up
private boolean setPlaying(boolean playing, boolean resetFocus) {
	if (player.isPlaying() != playing) {
		if (resetFocus && player.isAudioPresent()) {
			if (playing) {
				if (audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN)
						!= AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
					return false;
				}
			} else {
				audioManager.abandonAudioFocus(this);
			}
		}
		player.setPlaying(playing);
		pausedByTransientLossOfFocus = false;
	}
	return true;
}
 
Example 4
Source File: AudioTrackManagerDualNormal.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
private int getTTSAudioTrackFocus(int ttsType) {
    setTTSType(ttsType);
    if (ttsType == PCMPlayerUtils.TTS_TYPE_VR) {
        return 0;
    }

    int audioFocusType;

    audioFocusType = AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK;

    int ttsAudioTrackType = VehicleFactoryAdapter.getInstance().getTTSAudioTrackStreamType();
    int result = mAM.requestAudioFocus(mTTSAudioFocusListener, ttsAudioTrackType, audioFocusType);
    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        LogUtil.d(TAG, "tts audio track get successfully!");

        return 0;
    } else {
        LogUtil.d(TAG, "tts audio track get failed!");

        return -1;
    }

}
 
Example 5
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 6
Source File: AudioTrackManagerSingle.java    From apollo-DuerOS with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @return 0:success; 1:failed;
 */
private int getAudioTrackFocus() {
    // Request audio focus for playback
    int result =
            mAM.requestAudioFocus(mAudioFocusListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);

    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        LogUtil.d(TAG, "audio track get successfully!");

        return 0;
    } else {
        LogUtil.d(TAG, "audio track get failed!");

        return -1;
    }
}
 
Example 7
Source File: BaseIjkVideoView.java    From youqu_master with Apache License 2.0 6 votes vote down vote up
/**
 * Requests to obtain the audio focus
 *
 * @return True if the focus was granted
 */
boolean requestFocus() {
    if (currentFocus == AudioManager.AUDIOFOCUS_GAIN) {
        return true;
    }

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

    int status = mAudioManager.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 8
Source File: AudioFocusManager.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
public boolean requestAudioFocus() {
    RunMediaPlayer.playSilentSound(ContextHolder.getContext());
    final int request;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && mFocusRequest != null) {
        request = audioManager.requestAudioFocus(mFocusRequest);
    } else {
        request = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
    return (request == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
}
 
Example 9
Source File: LinphoneManager.java    From Linphone4Android with GNU General Public License v3.0 5 votes vote down vote up
private void requestAudioFocus(int stream){
	if (!mAudioFocused){
		int res = mAudioManager.requestAudioFocus(null, stream, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT );
		Log.d("Audio focus requested: " + (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED ? "Granted" : "Denied"));
		if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) mAudioFocused=true;
	}
}
 
Example 10
Source File: ReadAloudService.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
/**
 * @return 音频焦点
 */
private boolean requestFocus() {
    if (!isAudio) {
        MediaManager.playSilentSound(this);
    }
    int request;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        request = audioManager.requestAudioFocus(mFocusRequest);
    } else {
        request = audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
    }
    return (request == AudioManager.AUDIOFOCUS_REQUEST_GRANTED);
}
 
Example 11
Source File: VideoConsumptionExampleWithExoPlayerFragment.java    From tv-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ExoPlayerAdapter playerAdapter = new ExoPlayerAdapter(getActivity());
    playerAdapter.setAudioStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
    mMediaPlayerGlue = new VideoMediaPlayerGlue(getActivity(), playerAdapter);
    mMediaPlayerGlue.setHost(mHost);
    AudioManager audioManager = (AudioManager) getActivity()
            .getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.w(TAG, "video player cannot obtain audio focus!");
    }

    mMediaPlayerGlue.setMode(PlaybackControlsRow.RepeatAction.NONE);
    MediaMetaData intentMetaData = getActivity().getIntent().getParcelableExtra(
            VideoExampleActivity.TAG);
    if (intentMetaData != null) {
        mMediaPlayerGlue.setTitle(intentMetaData.getMediaTitle());
        mMediaPlayerGlue.setSubtitle(intentMetaData.getMediaArtistName());
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(
                Uri.parse(intentMetaData.getMediaSourcePath()));
    } else {
        mMediaPlayerGlue.setTitle("Diving with Sharks");
        mMediaPlayerGlue.setSubtitle("A Googler");
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(Uri.parse(URL));
    }
    PlaybackSeekDiskDataProvider.setDemoSeekProvider(mMediaPlayerGlue);
    playWhenReady(mMediaPlayerGlue);
    setBackgroundType(BG_LIGHT);
}
 
Example 12
Source File: MusicPlaybackService.java    From tv-samples with Apache License 2.0 5 votes vote down vote up
public void playMediaItem(MediaMetaData mediaItemToPlay) {
    if (mediaItemToPlay == null) {
        throw new IllegalArgumentException("mediaItemToPlay is null!");
    }
    int mediaItemPos = findMediaItemPosition(mediaItemToPlay);
    if (mediaItemPos == -1) {
        throw new IllegalArgumentException("mediaItemToPlay not found in the media item list!");
    }

    if (mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.e(TAG, "playMediaItem cannot obtain audio focus!");
        return;
    }

    if (!mMediaSession.isActive()) {
        mMediaSession.setActive(true);
    }

    if (mCurrentMediaItem != null && mInitialized &&
            mCurrentMediaItem.getMediaSourceUri().equals(mediaItemToPlay.getMediaSourceUri())) {
        if (!isPlaying()) {
            // This media item had been already playing but is being paused. Will resume the player.
            // No need to reset the player
            play();
        }
    } else {
        mCurrentMediaPosition = mediaItemPos;
        notifyMediaItemChanged(mediaItemToPlay);
        prepareNewMedia();
    }
}
 
Example 13
Source File: PlayService.java    From music_player with Open Software License 3.0 5 votes vote down vote up
public boolean removeAudioFocus() {
    try {
        if (audioManager != null) {
            return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == audioManager.abandonAudioFocus(this);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}
 
Example 14
Source File: VideoConsumptionExampleWithExoPlayerFragment.java    From leanback-showcase with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ExoPlayerAdapter playerAdapter = new ExoPlayerAdapter(getActivity());
    playerAdapter.setAudioStreamType(AudioManager.USE_DEFAULT_STREAM_TYPE);
    mMediaPlayerGlue = new VideoMediaPlayerGlue(getActivity(), playerAdapter);
    mMediaPlayerGlue.setHost(mHost);
    AudioManager audioManager = (AudioManager) getActivity()
            .getSystemService(Context.AUDIO_SERVICE);
    if (audioManager.requestAudioFocus(mOnAudioFocusChangeListener, AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN) != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
        Log.w(TAG, "video player cannot obtain audio focus!");
    }

    mMediaPlayerGlue.setMode(PlaybackControlsRow.RepeatAction.NONE);
    MediaMetaData intentMetaData = getActivity().getIntent().getParcelableExtra(
            VideoExampleActivity.TAG);
    if (intentMetaData != null) {
        mMediaPlayerGlue.setTitle(intentMetaData.getMediaTitle());
        mMediaPlayerGlue.setSubtitle(intentMetaData.getMediaArtistName());
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(
                Uri.parse(intentMetaData.getMediaSourcePath()));
    } else {
        mMediaPlayerGlue.setTitle("Diving with Sharks");
        mMediaPlayerGlue.setSubtitle("A Googler");
        mMediaPlayerGlue.getPlayerAdapter().setDataSource(Uri.parse(URL));
    }
    PlaybackSeekDiskDataProvider.setDemoSeekProvider(mMediaPlayerGlue);
    playWhenReady(mMediaPlayerGlue);
    setBackgroundType(BG_LIGHT);
}
 
Example 15
Source File: MediaService.java    From Cirrus_depricated with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Requests the audio focus to the Audio Manager
 */
private void tryToGetAudioFocus() {
    if (mAudioFocus != AudioFocus.FOCUS
            && mAudioManager != null
            && (AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAudioManager.requestAudioFocus( this,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN))
            ) {
        mAudioFocus = AudioFocus.FOCUS;
    }
}
 
Example 16
Source File: LocalPlayback.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
/**
 * Try to get the system audio focus.
 */
private void tryToGetAudioFocus() {
    LogUtils.d(TAG, "tryToGetAudioFocus");
    if (mAudioFocus != AUDIO_FOCUSED) {
        int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
                AudioManager.AUDIOFOCUS_GAIN);
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            mAudioFocus = AUDIO_FOCUSED;
        }
    }
}
 
Example 17
Source File: AudioManagerCompat.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void abandonCallAudioFocus() {
  if (audioFocusRequest == null) {
    Log.w(TAG, "Don't currently have audio focus. Ignoring...");
    return;
  }

  int result = audioManager.abandonAudioFocusRequest(audioFocusRequest);

  if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
    Log.w(TAG, "Audio focus abandon failed. Result code: " + result);
  }

  audioFocusRequest = null;
}
 
Example 18
Source File: PlayerAdapter.java    From android-MediaBrowserService with Apache License 2.0 4 votes vote down vote up
private boolean requestAudioFocus() {
    final int result = mAudioManager.requestAudioFocus(this,
            AudioManager.STREAM_MUSIC,
            AudioManager.AUDIOFOCUS_GAIN);
    return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
}
 
Example 19
Source File: PlaybackService.java    From odyssey with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Jumps playback to the given index and position inside the song (in milliseconds)
 *
 * @param index    Position of the song to play
 * @param jumpTime Position inside the song (milliseconds)
 */
public void jumpToIndex(int index, int jumpTime) {
    // Cancel possible alerts registered within the AlarmManager
    cancelQuitAlert();

    // Stop playback before starting a new song. This ensures state safety
    mPlayer.stop();

    // Set mCurrentPlayingIndex to new song after checking the bounds
    if (index < mCurrentList.size() && index >= 0) {
        mCurrentPlayingIndex = index;

        /*
         * Make sure service is "started" so android doesn't handle it as a
         * "bound service"
         */
        Intent serviceStartIntent = new Intent(this, PlaybackService.class);
        serviceStartIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceStartIntent);
        } else {
            startService(serviceStartIntent);
        }

        // Get the item that is requested to be played.
        TrackModel item = mCurrentList.get(mCurrentPlayingIndex);

        // Request audio focus before doing anything
        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            // Abort command if audio focus was not granted
            return;
        }

        // Notify the PlaybackServiceStatusHelper that a new media session is started
        mPlaybackServiceStatusHelper.startMediaSession();

        // Try to start playback of the track url.
        try {
            mPlayer.play(item.getTrackURL(), jumpTime);
        } catch (GaplessPlayer.PlaybackException e) {
            // Handle an error of the play command
            handlePlaybackException(e);
        }

        // Sets the mNextPlayingIndex to the index just started, because the PlaybackStartListener will
        // set the mCurrentPlayingIndex to the mNextPlayingIndex. This ensures that no additional code
        // is necessary to handle playback start
        mNextPlayingIndex = index;
    } else if (index < 0 || index > mCurrentList.size()) {
        // Invalid index
        stop();
    }

}
 
Example 20
Source File: RNJWPlayerView.java    From react-native-jw-media-player with MIT License 4 votes vote down vote up
public void requestAudioFocus() {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            if (hasAudioFocus) {
                return;
            }

            if (audioManager != null) {
                AudioAttributes playbackAttributes = new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) // CONTENT_TYPE_SPEECH
                        .build();
                focusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                        .setAudioAttributes(playbackAttributes)
                        .setAcceptsDelayedFocusGain(true)
//                    .setWillPauseWhenDucked(true)
                        .setOnAudioFocusChangeListener(this)
                        .build();

                int res = audioManager.requestAudioFocus(focusRequest);
                synchronized(focusLock) {
                    if (res == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
                        playbackNowAuthorized = false;
                    } else if (res == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        playbackNowAuthorized = true;
                        hasAudioFocus = true;
                    } else if (res == AudioManager.AUDIOFOCUS_REQUEST_DELAYED) {
                        playbackDelayed = true;
                        playbackNowAuthorized = false;
                    }
                }
                Log.e(TAG, "audioRequest: " + res);
            }
        }
        else {
            int result = 0;
            if (audioManager != null) {
                if (hasAudioFocus) {
                    return;
                }

                result = audioManager.requestAudioFocus(this,
                        // Use the music stream.
                        AudioManager.STREAM_MUSIC,
                        // Request permanent focus.
                        AudioManager.AUDIOFOCUS_GAIN);
            }
            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                hasAudioFocus = true;
            }
            Log.e(TAG, "audioRequest: " + result);
        }
    }