android.support.v4.media.session.PlaybackStateCompat Java Examples

The following examples show how to use android.support.v4.media.session.PlaybackStateCompat. 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: PlayerService.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void onPause() {
	super.onPause();
	if (mp == null || mediaSession == null) {
		return;
	}

	mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
										  .setState(PlaybackStateCompat.STATE_PAUSED, 0, 0.0f)
										  .setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE).build());

	mp.pause();
	buildNotification( generateAction( R.drawable.ic_play_arrow_black_36dp, getString(R.string.play), ACTION_PLAY ) );

	if (mResultReceiver != null) {
		mResultReceiver.send(DELEGATE_PAUSE, null);
	}
}
 
Example #2
Source File: MediaControlsHelper.java    From AcDisplay with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void onPlaybackStateChanged(int state) {
    Check.getInstance().isInMainThread();
    switch (state) {
        case PlaybackStateCompat.STATE_PLAYING:
            mHandler.removeMessages(H.MSG_HIDE_MEDIA_WIDGET);
            if (!mShowing) {
                mShowing = true;
                notifyOnStateChanged();
            }
            break;
        default:
            if (mShowing) {
                int delay = state == PlaybackStateCompat.STATE_NONE ? 500 : DELAY;
                mHandler.sendEmptyMessageDelayed(H.MSG_HIDE_MEDIA_WIDGET, delay);
            }
            break;
    }
}
 
Example #3
Source File: MusicControlNotification.java    From react-native-music-control with MIT License 6 votes vote down vote up
public synchronized void updateActions(long mask, Map<String, Integer> options) {
    play = createAction("play", "Play", mask, PlaybackStateCompat.ACTION_PLAY, play);
    pause = createAction("pause", "Pause", mask, PlaybackStateCompat.ACTION_PAUSE, pause);
    stop = createAction("stop", "Stop", mask, PlaybackStateCompat.ACTION_STOP, stop);
    next = createAction("next", "Next", mask, PlaybackStateCompat.ACTION_SKIP_TO_NEXT, next);
    previous = createAction("previous", "Previous", mask, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS, previous);

    if (options != null && options.containsKey("skipForward") && (options.get("skipForward") == 10 || options.get("skipForward") == 5 || options.get("skipForward") == 30)) {
        skipForward = createAction("skip_forward_" + options.get("skipForward").toString(), "Skip Forward", mask, PlaybackStateCompat.ACTION_FAST_FORWARD, skipForward);
    } else {
        skipForward = createAction("skip_forward_10", "Skip Forward", mask, PlaybackStateCompat.ACTION_FAST_FORWARD, skipForward);
    }

    if (options != null && options.containsKey("skipBackward") && (options.get("skipBackward") == 10 || options.get("skipBackward") == 5 || options.get("skipBackward") == 30)) {
        skipBackward = createAction("skip_backward_" + options.get("skipBackward").toString(), "Skip Backward", mask, PlaybackStateCompat.ACTION_REWIND, skipBackward);
    } else {
        skipBackward = createAction("skip_backward_10", "Skip Backward", mask, PlaybackStateCompat.ACTION_REWIND, skipBackward);
    }
}
 
Example #4
Source File: MediaSessionPlaybackReporter.java    From PainlessMusicPlayer with Apache License 2.0 6 votes vote down vote up
@Override
public void reportPlaybackStateChanged(
        @NonNull final PlaybackState state,
        @Nullable final CharSequence errorMessage) {
    @PlaybackStateCompat.State final int playbackState = toPlaybackStateCompat(state);
    final boolean isPlaying = playbackState == PlaybackStateCompat.STATE_PLAYING;
    final PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder()
            .setActions(PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE
                    | PlaybackStateCompat.ACTION_PLAY_PAUSE
                    | PlaybackStateCompat.ACTION_STOP
                    | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                    | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
                    | PlaybackStateCompat.ACTION_SEEK_TO
                    | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH)
            .setState(playbackState, 0, isPlaying ? 1 : 0);

    if (errorMessage != null) {
        builder.setErrorMessage(PlaybackStateCompat.ERROR_CODE_APP_ERROR, errorMessage);
    }

    mMediaSession.setPlaybackState(builder.build());
}
 
Example #5
Source File: MediaSessionPlaybackActivity.java    From android-PictureInPicture with Apache License 2.0 6 votes vote down vote up
@Override
public void onSkipToPrevious() {
    super.onSkipToPrevious();
    movieView.startVideo();
    if (indexInPlaylist > 0) {
        indexInPlaylist--;
        if (indexInPlaylist <= 0) {
            updatePlaybackState(
                    PlaybackStateCompat.STATE_PLAYING,
                    MEDIA_ACTIONS_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_NEXT,
                    movieView.getCurrentPosition(),
                    movieView.getVideoResourceId());
        } else {
            updatePlaybackState(
                    PlaybackStateCompat.STATE_PLAYING,
                    MEDIA_ACTIONS_ALL,
                    movieView.getCurrentPosition(),
                    movieView.getVideoResourceId());
        }
    }
}
 
Example #6
Source File: MediaNotificationManager.java    From react-native-audio-streaming-player with MIT License 6 votes vote down vote up
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
    if (mPlaybackState == null || !mStarted) {
        mService.stopForeground(true);
        return;
    }

    if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING && mPlaybackState.getPosition() >= 0) {
        builder
            .setWhen(System.currentTimeMillis() - mPlaybackState.getPosition())
            .setShowWhen(true)
            .setUsesChronometer(true);
    } else {
        builder
            .setWhen(0)
            .setShowWhen(false)
            .setUsesChronometer(false);
    }

    // Make sure that the notification can be dismissed by the user when we are not playing:
    builder.setOngoing(mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
 
Example #7
Source File: PlaybackService.java    From VCL-Android with Apache License 2.0 6 votes vote down vote up
protected void publishState(int state) {
    if (mMediaSession == null)
        return;
    PlaybackStateCompat.Builder bob = new PlaybackStateCompat.Builder();
    bob.setActions(PLAYBACK_ACTIONS);
    switch (state) {
        case MediaPlayer.Event.Playing:
            bob.setState(PlaybackStateCompat.STATE_PLAYING, -1, 1);
            break;
        case MediaPlayer.Event.Stopped:
            bob.setState(PlaybackStateCompat.STATE_STOPPED, -1, 0);
            break;
        default:
        bob.setState(PlaybackStateCompat.STATE_PAUSED, -1, 0);
    }
    PlaybackStateCompat pbState = bob.build();
    mMediaSession.setPlaybackState(pbState);
    mMediaSession.setActive(state != PlaybackStateCompat.STATE_STOPPED);
}
 
Example #8
Source File: AdapterMusic.java    From DMAudioStreamer with Apache License 2.0 6 votes vote down vote up
private Drawable getDrawableByState(Context context, int state) {
    switch (state) {
        case PlaybackStateCompat.STATE_NONE:
            Drawable pauseDrawable = ContextCompat.getDrawable(context, R.drawable.ic_play);
            DrawableCompat.setTintList(pauseDrawable, colorPlay);
            return pauseDrawable;
        case PlaybackStateCompat.STATE_PLAYING:
            AnimationDrawable animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.equalizer);
            DrawableCompat.setTintList(animation, colorPlay);
            animation.start();
            return animation;
        case PlaybackStateCompat.STATE_PAUSED:
            Drawable playDrawable = ContextCompat.getDrawable(context, R.drawable.equalizer);
            DrawableCompat.setTintList(playDrawable, colorPause);
            return playDrawable;
        default:
            Drawable noneDrawable = ContextCompat.getDrawable(context, R.drawable.ic_play);
            DrawableCompat.setTintList(noneDrawable, colorPlay);
            return noneDrawable;
    }
}
 
Example #9
Source File: VolumePanel.java    From Noyze with Apache License 2.0 6 votes vote down vote up
/**
 * Notified when the play state has changed. Unfortunately, without a standardized API this
 * may or may not be called (with or without all fields), and may only work for certain
 * apps/ music players.
 */
public void onPlayStateChanged(Pair<MediaMetadataCompat, PlaybackStateCompat> mediaInfo) {
    LOGI("VolumePanel", "onPlayStateChanged()");

    // If the event was just an update to the play state, handle accordingly.
    mMusicActive = RemoteControlCompat.isPlaying(mediaInfo.second);
    LOGI("VolumePanel", "isPlayState(playing=" + mMusicActive + ")");

    // Update the play state if we've been given one.
    if (null != mAudioHelper && null == mediaInfo.second)
        mMusicActive = mAudioHelper.isLocalOrRemoteMusicActive();

    // Update the music package name based on RemoteController/ magic.
    if (null != mediaInfo.first)
        musicPackageName = mediaInfo.first.getString(RemoteControlCompat.METADATA_KEY_PACKAGE);

    // TRACK: when the user starts and ends playing a song.
    mMediaInfo = mediaInfo;
}
 
Example #10
Source File: PlayerNotification.java    From blade-player with GNU General Public License v3.0 6 votes vote down vote up
PlayerNotification(PlayerService service)
{
    this.mService = service;

    mNotificationManager = NotificationManagerCompat.from(service);

    mPlayAction = new NotificationCompat.Action(R.drawable.play_arrow, mService.getString(R.string.play),
            MediaButtonReceiver.buildMediaButtonPendingIntent(mService, PlaybackStateCompat.ACTION_PLAY));
    mPauseAction = new NotificationCompat.Action(R.drawable.pause_notif, mService.getString(R.string.pause),
            MediaButtonReceiver.buildMediaButtonPendingIntent(mService, PlaybackStateCompat.ACTION_PAUSE));
    mNextAction = new NotificationCompat.Action(R.drawable.next_arrow_notif, mService.getString(R.string.next),
            MediaButtonReceiver.buildMediaButtonPendingIntent(mService, PlaybackStateCompat.ACTION_SKIP_TO_NEXT));
    mPrevAction = new NotificationCompat.Action(R.drawable.prev_arrow_notif, mService.getString(R.string.prev),
            MediaButtonReceiver.buildMediaButtonPendingIntent(mService, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS));

    mNotificationManager.cancelAll();
}
 
Example #11
Source File: RemoteControlKitKat.java    From Noyze with Apache License 2.0 6 votes vote down vote up
/**
 * A map between {@link android.media.RemoteControlClient} flags and {@link android.media.session.PlaybackState} actions.
 * @return The value to provide for {@link android.media.session.PlaybackState} for actions.
 */
private static long getPlaybackStateActions(final int transportControlFlags) {
    final Map<Integer, Long> FLAG_MAP = new HashMap<>();
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_STOP, PlaybackStateCompat.ACTION_STOP);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_NEXT, PlaybackStateCompat.ACTION_SKIP_TO_NEXT);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_PREVIOUS, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_PAUSE, PlaybackStateCompat.ACTION_PAUSE);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_FAST_FORWARD, PlaybackStateCompat.ACTION_FAST_FORWARD);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_REWIND, PlaybackStateCompat.ACTION_REWIND);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_PLAY, PlaybackStateCompat.ACTION_PLAY);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_PLAY_PAUSE, PlaybackStateCompat.ACTION_PLAY_PAUSE);
    FLAG_MAP.put(RemoteControlClient.FLAG_KEY_MEDIA_RATING, PlaybackStateCompat.ACTION_SET_RATING);
    long actions = 0;
    for (Map.Entry<Integer, Long> flags : FLAG_MAP.entrySet()) {
        if ((transportControlFlags & flags.getKey()) == flags.getKey()) {
            if (actions == 0)
                actions = flags.getValue();
            else
                actions |= flags.getValue();
        }
    }
    return actions;
}
 
Example #12
Source File: NotificationUtil.java    From Prodigal with Apache License 2.0 6 votes vote down vote up
private NotificationCompat.Builder notificationBuilder(PlayerService context, MediaSessionCompat session) {
    MediaControllerCompat controller = session.getController();
    MediaMetadataCompat mediaMetadata = controller.getMetadata();
    MediaDescriptionCompat description = mediaMetadata.getDescription();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setSubText(description.getDescription())
            .setLargeIcon(mediaMetadata.getBitmap(MediaMetadataCompat.METADATA_KEY_ART))
            .setContentIntent(clickIntent)
            .setDeleteIntent(
                    MediaButtonReceiver.buildMediaButtonPendingIntent(context, receiverName, PlaybackStateCompat.ACTION_STOP))
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    return builder;
}
 
Example #13
Source File: PlaybackManager.java    From Melophile with Apache License 2.0 6 votes vote down vote up
private long getAvailableActions() {
  long actions =
          PlaybackStateCompat.ACTION_PLAY_PAUSE |
                  PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID |
                  PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH |
                  PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                  PlaybackStateCompat.ACTION_SKIP_TO_NEXT;
  if (playback.isPlaying()) {
    actions |= PlaybackStateCompat.ACTION_PAUSE;
  } else {
    actions |= PlaybackStateCompat.ACTION_PLAY;
  }
  //
  if (isRepeat) {
    actions |= PlaybackStateCompat.ACTION_SET_REPEAT_MODE;
  }
  //
  if (isShuffle) {
    actions |= PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE_ENABLED;
  }
  return actions;
}
 
Example #14
Source File: MediaStyleHelper.java    From AndroidAudioExample with MIT License 6 votes vote down vote up
/**
 * Build a notification using the information from the given media session. Makes heavy use
 * of {@link MediaMetadataCompat#getDescription()} to extract the appropriate information.
 *
 * @param context      Context used to construct the notification.
 * @param mediaSession Media session to get information.
 * @return A pre-built notification with information from the given media session.
 */
static NotificationCompat.Builder from(Context context, MediaSessionCompat mediaSession) {
    MediaControllerCompat controller = mediaSession.getController();
    MediaMetadataCompat mediaMetadata = controller.getMetadata();
    MediaDescriptionCompat description = mediaMetadata.getDescription();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setSubText(description.getDescription())
            .setLargeIcon(description.getIconBitmap())
            .setContentIntent(controller.getSessionActivity())
            .setDeleteIntent(
                    MediaButtonReceiver.buildMediaButtonPendingIntent(context, PlaybackStateCompat.ACTION_STOP))
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    return builder;
}
 
Example #15
Source File: X8B2oxFile.java    From FimiX8-RE with MIT License 6 votes vote down vote up
public String calculationLen() {
    long fileS = X8FileHelper.getDirSize(this.file);
    String size = "0B";
    DecimalFormat df = new DecimalFormat("#.00");
    if (fileS < 1024) {
        if (fileS == 0) {
            return "0.00B";
        }
        return df.format((double) fileS) + "B";
    } else if (fileS < PlaybackStateCompat.ACTION_SET_CAPTIONING_ENABLED) {
        return df.format(((double) fileS) / 1024.0d) + "K";
    } else {
        if (fileS < 1073741824) {
            return df.format(((double) fileS) / 1048576.0d) + "M";
        }
        return df.format(((double) fileS) / 1.073741824E9d) + "G";
    }
}
 
Example #16
Source File: MediaSessionPlaybackActivity.java    From android-PictureInPicture with Apache License 2.0 6 votes vote down vote up
@Override
public void onSkipToNext() {
    super.onSkipToNext();
    movieView.startVideo();
    if (indexInPlaylist < PLAYLIST_SIZE) {
        indexInPlaylist++;
        if (indexInPlaylist >= PLAYLIST_SIZE) {
            updatePlaybackState(
                    PlaybackStateCompat.STATE_PLAYING,
                    MEDIA_ACTIONS_PLAY_PAUSE | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS,
                    movieView.getCurrentPosition(),
                    movieView.getVideoResourceId());
        } else {
            updatePlaybackState(
                    PlaybackStateCompat.STATE_PLAYING,
                    MEDIA_ACTIONS_ALL,
                    movieView.getCurrentPosition(),
                    movieView.getVideoResourceId());
        }
    }
}
 
Example #17
Source File: MediaSessionWrapper.java    From Cheerleader with Apache License 2.0 6 votes vote down vote up
/**
 * Propagate the playback state to the media session and the lock screen remote control.
 * <p/>
 * See also :
 * {@link fr.tvbarthel.cheerleader.library.media.MediaSessionWrapper#PLAYBACK_STATE_STOPPED}
 * {@link fr.tvbarthel.cheerleader.library.media.MediaSessionWrapper#PLAYBACK_STATE_PLAYING}
 * {@link fr.tvbarthel.cheerleader.library.media.MediaSessionWrapper#PLAYBACK_STATE_PAUSED}
 *
 * @param state playback state.
 */
@SuppressWarnings("deprecation")
public void setPlaybackState(int state) {
    switch (state) {
        case PLAYBACK_STATE_STOPPED:
            setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_STOPPED);
            setMediaSessionCompatPlaybackState(PlaybackStateCompat.STATE_STOPPED);
            mMediaSession.setActive(false);
            break;
        case PLAYBACK_STATE_PLAYING:
            setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);
            setMediaSessionCompatPlaybackState(PlaybackStateCompat.STATE_PLAYING);
            mMediaSession.setActive(true);
            break;
        case PLAYBACK_STATE_PAUSED:
            setRemoteControlClientPlaybackState(RemoteControlClient.PLAYSTATE_PAUSED);
            setMediaSessionCompatPlaybackState(PlaybackStateCompat.STATE_PAUSED);
            break;
        default:
            Log.e(TAG, "Unknown playback state.");
            break;
    }
}
 
Example #18
Source File: MediaNotificationManager.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
private void setNotificationPlaybackState(NotificationCompat.Builder builder) {
    LogUtils.d(TAG, "updateNotificationPlaybackState. mPlaybackState=" + mPlaybackState);
    if (mPlaybackState == null || !mStarted) {
        LogUtils.d(TAG, "updateNotificationPlaybackState. cancelling notification!");
        mService.stopForeground(true);
        return;
    }
    if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING
            && mPlaybackState.getPosition() >= 0) {
        LogUtils.d(TAG, "updateNotificationPlaybackState. updating playback position to ",
                (System.currentTimeMillis() - mPlaybackState.getPosition()) / 1000, " seconds");
        builder
                .setWhen(System.currentTimeMillis() - mPlaybackState.getPosition())
                .setShowWhen(true)
                .setUsesChronometer(true);
    } else {
        LogUtils.d(TAG, "updateNotificationPlaybackState. hiding playback position");
        builder
                .setWhen(0)
                .setShowWhen(false)
                .setUsesChronometer(false);
    }

    // Make sure that the notification can be dismissed by the user when we are not playing:
    builder.setOngoing(mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING);
}
 
Example #19
Source File: MusicControlModule.java    From react-native-music-control with MIT License 6 votes vote down vote up
@Override
public Map<String, Object> getConstants() {
    Map<String, Object> map = new HashMap<>();
    map.put("STATE_ERROR", PlaybackStateCompat.STATE_ERROR);
    map.put("STATE_STOPPED", PlaybackStateCompat.STATE_STOPPED);
    map.put("STATE_PLAYING", PlaybackStateCompat.STATE_PLAYING);
    map.put("STATE_PAUSED", PlaybackStateCompat.STATE_PAUSED);
    map.put("STATE_BUFFERING", PlaybackStateCompat.STATE_BUFFERING);

    map.put("RATING_HEART", RatingCompat.RATING_HEART);
    map.put("RATING_THUMBS_UP_DOWN", RatingCompat.RATING_THUMB_UP_DOWN);
    map.put("RATING_3_STARS", RatingCompat.RATING_3_STARS);
    map.put("RATING_4_STARS", RatingCompat.RATING_4_STARS);
    map.put("RATING_5_STARS", RatingCompat.RATING_5_STARS);
    map.put("RATING_PERCENTAGE", RatingCompat.RATING_PERCENTAGE);
    return map;
}
 
Example #20
Source File: MusicService.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
private void refreshMediaSession(int playState, Bitmap resource) {
    if (resource == null) {
        resource = BitmapFactory.decodeResource(getResources(), R.drawable.icon_album_default);
    }
    MusicPlayBean musicPlayBean = MusicPlayerManager.getInstance().getMusicPlayBean();
    mediaSessionCompat.setMetadata(new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, musicPlayBean.getArtistName())
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, musicPlayBean.getArtistName())
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, musicPlayBean.getAlbumName())
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, musicPlayBean.getSongName())
            .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, musicPlayBean.getDuration())
            .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, resource)
            .build());
    mediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder()
            .setState(playState, mMusicBinder.getPosition(), 1.0f)
            .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE |
                    PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
            .build());
}
 
Example #21
Source File: FullScreenPlayerActivity.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
private void connectToSession(MediaSessionCompat.Token token) {
    try {
        mMediaController = new MediaControllerCompat(FullScreenPlayerActivity.this, token);
        if (mMediaController.getMetadata() == null) {
            finish();
            return;
        }

        mMediaController.registerCallback(mCallback);
        PlaybackStateCompat state = mMediaController.getPlaybackState();
        updatePlaybackState(state);
        MediaMetadataCompat metadata = mMediaController.getMetadata();
        if (metadata != null) {
            updateMediaDescription(metadata.getDescription());
            updateDuration(metadata);
        }
        updateProgress();
        if (state != null && (state.getState() == PlaybackStateCompat.STATE_PLAYING ||
                state.getState() == PlaybackStateCompat.STATE_BUFFERING)) {
            scheduleSeekbarUpdate();
        }

    } catch (RemoteException e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
/**
     * Pauses video
     */
    private void pauseVideo()
    {
        if (playState == PlaybackStateCompat.STATE_PLAYING) {
            // Pause media player and cancel the 'foreground service' state.
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                currentPosition = mediaPlayer.getCurrentPosition();
            }
            // while paused, retain the MediaPlayer but give up audio focus
            relaxResources(false);
        }
        playState = PlaybackStateCompat.STATE_PAUSED;
        unregisterAudioNoisyReceiver();
//        stopForeground(true);
//        if (mCallback != null) {
//            mCallback.onPlaybackStatusChanged(playState);
//        }
    }
 
Example #23
Source File: LocalPlayback.java    From LyricHere with Apache License 2.0 5 votes vote down vote up
/**
 * Called when MediaPlayer has completed a seek
 *
 * @see OnSeekCompleteListener
 */
@Override
public void onSeekComplete(MediaPlayer mp) {
    LogUtils.d(TAG, "onSeekComplete from MediaPlayer:", mp.getCurrentPosition());
    mCurrentPosition = mp.getCurrentPosition();
    if (mState == PlaybackStateCompat.STATE_BUFFERING) {
        mMediaPlayer.start();
        mState = PlaybackStateCompat.STATE_PLAYING;
    }
    if (mCallback != null) {
        mCallback.onPlaybackStatusChanged(mState);
    }
}
 
Example #24
Source File: MediaController.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Disable pause or seek buttons if the stream cannot be paused or seeked.
 * This requires the control interface to be a MediaPlayerControlExt
 */
void updateButtons() {
    if (mDelegate == null) return;

    long flags = mDelegate.getActionFlags();
    boolean enabled = isEnabled();
    if (mPauseButton != null) {
        boolean needPlayPauseButton = (flags & PlaybackStateCompat.ACTION_PLAY) != 0
                || (flags & PlaybackStateCompat.ACTION_PAUSE) != 0;
        mPauseButton.setEnabled(enabled && needPlayPauseButton);
    }
    if (mRewButton != null) {
        mRewButton.setEnabled(enabled && (flags & PlaybackStateCompat.ACTION_REWIND) != 0);
    }
    if (mFfwdButton != null) {
        mFfwdButton.setEnabled(
                enabled && (flags & PlaybackStateCompat.ACTION_FAST_FORWARD) != 0);
    }
    if (mPrevButton != null) {
        mShowPrev =
                (flags & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0 || mPrevListener != null;
        mPrevButton.setEnabled(enabled && mShowPrev);
    }
    if (mNextButton != null) {
        mShowNext = (flags & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0
                || mNextListener != null;
        mNextButton.setEnabled(enabled && mShowNext);
    }
}
 
Example #25
Source File: ReadAloudService.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
private void updateMediaSessionPlaybackState() {
    mediaSessionCompat.setPlaybackState(
            new PlaybackStateCompat.Builder()
                    .setActions(MEDIA_SESSION_ACTIONS)
                    .setState(speak ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED,
                            nowSpeak, 1)
                    .build());
}
 
Example #26
Source File: ReadAloudService.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
private void updateMediaSessionPlaybackState() {
    mediaSessionCompat.setPlaybackState(
            new PlaybackStateCompat.Builder()
                    .setActions(MEDIA_SESSION_ACTIONS)
                    .setState(speak ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED,
                            nowSpeak, 1)
                    .build());
}
 
Example #27
Source File: MediaNotificationManager.java    From react-native-streaming-audio-player with MIT License 5 votes vote down vote up
private void addPlayPauseAction(NotificationCompat.Builder builder) {
    String label;
    int icon;
    PendingIntent intent;
    if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
        label = "pause";
        icon = R.drawable.ic_pause_white_24dp;
        intent = mPauseIntent;
    } else {
        label = "play";
        icon = R.drawable.ic_play_arrow_white_24dp;
        intent = mPlayIntent;
    }
    builder.addAction(new NotificationCompat.Action(icon, label, intent));
}
 
Example #28
Source File: Playback.java    From react-native-audio-streaming-player with MIT License 5 votes vote down vote up
public void seekTo(int position) {
    if (mMediaPlayer == null) {
        // If we do not have a current media player, simply update the current position
        mCurrentPosition = position;
    } else {
        if (mMediaPlayer.isPlaying()) {
            mState = PlaybackStateCompat.STATE_BUFFERING;
        }
        registerAudioNoisyReceiver();
        mMediaPlayer.seekTo(position);
        if (mCallback != null) {
            mCallback.onPlaybackStateChanged(mState);
        }
    }
}
 
Example #29
Source File: RadioPlayerService.java    From monkeyboard-radio-android with GNU General Public License v3.0 5 votes vote down vote up
private void onConnectedSequence() {
    handleAction(new Runnable() {
        @Override
        public void run() {
            radio.waitForReady();
            // When the radio first connects, try to get the number of programs stored,
            // and set the stereo mode to stereo
            radioTotalStoredPrograms = radio.getTotalPrograms();

            updateBoardStereoModeAction();
        }
    });

    if (playerNotification != null) {
        playerNotification.cancel();
    }

    playerNotification = new RadioPlayerNotification(this);

    if (queuedAction != null) {
        handleAction(queuedAction);
        queuedAction = null;
    }

    if (getRadioMode() == RadioDevice.Values.STREAM_MODE_DAB) {
        handleSetDabChannelRequest(getCurrentDabChannelIndex());
    } else {
        handleSetFmFrequencyRequest(getCurrentFmFrequency());
    }

    if (getPlaybackState() == PlaybackStateCompat.STATE_PLAYING) {
        handlePlayRequest();
    }
}
 
Example #30
Source File: Playback.java    From react-native-streaming-audio-player with MIT License 5 votes vote down vote up
public void stop() {
    mState = PlaybackStateCompat.STATE_STOPPED;
    if (mCallback != null) {
        mCallback.onPlaybackStateChanged(mState);
    }
    mCurrentPosition = 0;
    // Give up Audio focus
    giveUpAudioFocus();
    unregisterAudioNoisyReceiver();
    // Relax all resources
    relaxResources(true);
}