Java Code Examples for android.support.v4.media.session.PlaybackStateCompat#STATE_STOPPED

The following examples show how to use android.support.v4.media.session.PlaybackStateCompat#STATE_STOPPED . 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: LocalPlayback.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
@Override
public int getState()
{
    if (exoPlayer == null) {
        return exoPlayerNullIsStopped ? PlaybackStateCompat.STATE_STOPPED : PlaybackStateCompat.STATE_NONE;
    }

    switch (exoPlayer.getPlaybackState()) {
        case STATE_IDLE:
            return PlaybackStateCompat.STATE_PAUSED;
        case STATE_BUFFERING:
            return PlaybackStateCompat.STATE_BUFFERING;
        case STATE_READY:
            return exoPlayer.getPlayWhenReady() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_PAUSED;
        case STATE_ENDED:
            return PlaybackStateCompat.STATE_PAUSED;
        default:
            return PlaybackStateCompat.STATE_NONE;
    }
}
 
Example 2
Source File: MusicService.java    From android-MediaBrowserService with Apache License 2.0 6 votes vote down vote up
@Override
public void onPlaybackStateChange(PlaybackStateCompat state) {
    // Report the state to the MediaSession.
    mSession.setPlaybackState(state);

    // Manage the started state of this service.
    switch (state.getState()) {
        case PlaybackStateCompat.STATE_PLAYING:
            mServiceManager.moveServiceToStartedState(state);
            break;
        case PlaybackStateCompat.STATE_PAUSED:
            mServiceManager.updateNotificationForPause(state);
            break;
        case PlaybackStateCompat.STATE_STOPPED:
            mServiceManager.moveServiceOutOfStartedState(state);
            break;
    }
}
 
Example 3
Source File: PlaybackControlsFragment.java    From LyricHere with Apache License 2.0 6 votes vote down vote up
@Override
public void onClick(View v) {
    PlaybackStateCompat stateObj = mMediaControllerProvider.getSupportMediaController().getPlaybackState();
    final int state = stateObj == null ?
            PlaybackStateCompat.STATE_NONE : stateObj.getState();
    LogUtils.d(TAG, "Button pressed, in state " + state);
    switch (v.getId()) {
        case R.id.play_pause:
            LogUtils.d(TAG, "Play button pressed, in state " + state);
            if (state == PlaybackStateCompat.STATE_PAUSED ||
                    state == PlaybackStateCompat.STATE_STOPPED ||
                    state == PlaybackStateCompat.STATE_NONE) {
                playMedia();
            } else if (state == PlaybackStateCompat.STATE_PLAYING ||
                    state == PlaybackStateCompat.STATE_BUFFERING ||
                    state == PlaybackStateCompat.STATE_CONNECTING) {
                pauseMedia();
            }
            break;
    }
}
 
Example 4
Source File: PlayerService.java    From AndroidAudioExample with MIT License 6 votes vote down vote up
@Override
public void onStop() {
    if (exoPlayer.getPlayWhenReady()) {
        exoPlayer.setPlayWhenReady(false);
        unregisterReceiver(becomingNoisyReceiver);
    }

    if (audioFocusRequested) {
        audioFocusRequested = false;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            audioManager.abandonAudioFocusRequest(audioFocusRequest);
        } else {
            audioManager.abandonAudioFocus(audioFocusChangeListener);
        }
    }

    mediaSession.setActive(false);

    mediaSession.setPlaybackState(stateBuilder.setState(PlaybackStateCompat.STATE_STOPPED, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1).build());
    currentState = PlaybackStateCompat.STATE_STOPPED;

    refreshNotificationAndForegroundStatus(currentState);

    stopSelf();
}
 
Example 5
Source File: LocalPlayback.java    From klingar with Apache License 2.0 6 votes vote down vote up
@Override @State public int getState() {
  if (exoPlayer == null) {
    return exoPlayerNullIsStopped ? PlaybackStateCompat.STATE_STOPPED
        : PlaybackStateCompat.STATE_NONE;
  }
  switch (exoPlayer.getPlaybackState()) {
    case Player.STATE_IDLE:
    case Player.STATE_ENDED:
      return PlaybackStateCompat.STATE_PAUSED;
    case Player.STATE_BUFFERING:
      return PlaybackStateCompat.STATE_BUFFERING;
    case Player.STATE_READY:
      return exoPlayer.getPlayWhenReady() ? PlaybackStateCompat.STATE_PLAYING
          : PlaybackStateCompat.STATE_PAUSED;
    default:
      return PlaybackStateCompat.STATE_NONE;
  }
}
 
Example 6
Source File: TrackNotification.java    From Melophile with Apache License 2.0 5 votes vote down vote up
public void updatePlaybackState(PlaybackStateCompat playbackState) {
  this.playbackState = playbackState;
  if (playbackState.getState() == PlaybackStateCompat.STATE_STOPPED ||
          playbackState.getState() == PlaybackStateCompat.STATE_NONE) {
    stopNotification();
  } else {
    updateNotification();
  }
}
 
Example 7
Source File: MediaPlayback.java    From Melophile with Apache License 2.0 5 votes vote down vote up
@Override
public void stopPlayer() {
  playerState = PlaybackStateCompat.STATE_STOPPED;
  if (player != null) {
    player.release();
    player = null;
  }
}
 
Example 8
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);
}
 
Example 9
Source File: VinylCastService.java    From vinyl-cast with MIT License 5 votes vote down vote up
private void updateMediaSession() {
    int state = isRecording() ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_STOPPED;
    long action = isRecording() ? PlaybackStateCompat.ACTION_STOP : PlaybackStateCompat.ACTION_PLAY;
    mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
            .setState(state, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1.0f)
            .setActions(action)
            .build());
    mediaSession.setActive(isRecording());
}
 
Example 10
Source File: MediaNotificationManager.java    From react-native-audio-streaming-player with MIT License 5 votes vote down vote up
@Override
public void onPlaybackStateChanged(@NonNull PlaybackStateCompat state) {
    mPlaybackState = state;
    if (state.getState() == PlaybackStateCompat.STATE_STOPPED ||
            state.getState() == PlaybackStateCompat.STATE_NONE) {
        stopNotification();
    } else {
        Notification notification = createNotification();
        if (notification != null) {
            mNotificationManager.notify(NOTIFICATION_ID, notification);
        }
    }
}
 
Example 11
Source File: Playback.java    From react-native-audio-streaming-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);
}
 
Example 12
Source File: MediaPlayerAdapter.java    From android-MediaBrowserService with Apache License 2.0 5 votes vote down vote up
/**
 * Set the current capabilities available on this session. Note: If a capability is not
 * listed in the bitmask of capabilities then the MediaSession will not handle it. For
 * example, if you don't want ACTION_STOP to be handled by the MediaSession, then don't
 * included it in the bitmask that's returned.
 */
@PlaybackStateCompat.Actions
private long getAvailableActions() {
    long actions = PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
                   | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
                   | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
                   | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS;
    switch (mState) {
        case PlaybackStateCompat.STATE_STOPPED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                       | PlaybackStateCompat.ACTION_PAUSE;
            break;
        case PlaybackStateCompat.STATE_PLAYING:
            actions |= PlaybackStateCompat.ACTION_STOP
                       | PlaybackStateCompat.ACTION_PAUSE
                       | PlaybackStateCompat.ACTION_SEEK_TO;
            break;
        case PlaybackStateCompat.STATE_PAUSED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                       | PlaybackStateCompat.ACTION_STOP;
            break;
        default:
            actions |= PlaybackStateCompat.ACTION_PLAY
                       | PlaybackStateCompat.ACTION_PLAY_PAUSE
                       | PlaybackStateCompat.ACTION_STOP
                       | PlaybackStateCompat.ACTION_PAUSE;
    }
    return actions;
}
 
Example 13
Source File: MediaSessionManager.java    From react-native-jw-media-player with MIT License 5 votes vote down vote up
private void updatePlaybackState(PlayerState playerState) {
	PlaybackStateCompat.Builder newPlaybackState = getPlaybackStateBuilder();
	long capabilities = getCapabilities(playerState);
	//noinspection WrongConstant
	newPlaybackState.setActions(capabilities);

	int playbackStateCompat = PlaybackStateCompat.STATE_NONE;
	switch (playerState) {
		case PLAYING:
			playbackStateCompat = PlaybackStateCompat.STATE_PLAYING;
			break;
		case PAUSED:
			playbackStateCompat = PlaybackStateCompat.STATE_PAUSED;
			break;
		case BUFFERING:
			playbackStateCompat = PlaybackStateCompat.STATE_BUFFERING;
			break;
		case IDLE:
			if (mReceivedError) {
				playbackStateCompat = PlaybackStateCompat.STATE_ERROR;
			} else {
				playbackStateCompat = PlaybackStateCompat.STATE_STOPPED;
			}
			break;
	}

	if (mPlayer != null) {
		newPlaybackState.setState(playbackStateCompat, (long)mPlayer.getPosition(), mPlayer.getPlaybackRate()); // PLAYBACK_RATE
		mMediaSessionCompat.setPlaybackState(newPlaybackState.build());
		mNotificationWrapper
				.createNotification(mPlayer.getContext(), mMediaSessionCompat, capabilities);
	}
}
 
Example 14
Source File: PlayerMediaPlayer.java    From blade-player with GNU General Public License v3.0 4 votes vote down vote up
public PlaybackStateCompat getPlaybackState()
{
    long actions = PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
            | PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
            | PlaybackStateCompat.ACTION_SKIP_TO_NEXT
            | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS
            | PlaybackStateCompat.ACTION_SET_REPEAT_MODE
            | PlaybackStateCompat.ACTION_SET_SHUFFLE_MODE;

    int playbackState = 0;
    switch(currentState)
    {
        case PLAYER_STATE_PAUSED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_STOP
                    | PlaybackStateCompat.ACTION_SEEK_TO;
            playbackState = PlaybackStateCompat.STATE_PAUSED;
            break;

        case PLAYER_STATE_PLAYING:
            actions |= PlaybackStateCompat.ACTION_PAUSE
                    | PlaybackStateCompat.ACTION_STOP
                    | PlaybackStateCompat.ACTION_SEEK_TO;
            playbackState = PlaybackStateCompat.STATE_PLAYING;
            break;

        case PLAYER_STATE_STOPPED:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE;
            playbackState = PlaybackStateCompat.STATE_STOPPED;
            break;

        case PLAYER_STATE_NONE:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE;
            playbackState = PlaybackStateCompat.STATE_STOPPED;
            break;

        case PLAYER_STATE_DO_NOTHING:
            actions |= PlaybackStateCompat.ACTION_PLAY
                    | PlaybackStateCompat.ACTION_PAUSE;
            playbackState = PlaybackStateCompat.STATE_STOPPED;
    }

    final PlaybackStateCompat.Builder stateBuilder = new PlaybackStateCompat.Builder();
    stateBuilder.setActions(actions);
    stateBuilder.setState(playbackState, getCurrentPosition(), 1.0f, SystemClock.elapsedRealtime());
    return stateBuilder.build();
}
 
Example 15
Source File: MusicActivity.java    From DMAudioStreamer with Apache License 2.0 4 votes vote down vote up
@Override
public void updatePlaybackState(int state) {
    Logger.e("updatePlaybackState: ", "" + state);
    switch (state) {
        case PlaybackStateCompat.STATE_PLAYING:
            pgPlayPauseLayout.setVisibility(View.INVISIBLE);
            btn_play.Play();
            if (currentSong != null) {
                currentSong.setPlayState(PlaybackStateCompat.STATE_PLAYING);
                notifyAdapter(currentSong);
            }
            break;
        case PlaybackStateCompat.STATE_PAUSED:
            pgPlayPauseLayout.setVisibility(View.INVISIBLE);
            btn_play.Pause();
            if (currentSong != null) {
                currentSong.setPlayState(PlaybackStateCompat.STATE_PAUSED);
                notifyAdapter(currentSong);
            }
            break;
        case PlaybackStateCompat.STATE_NONE:
            currentSong.setPlayState(PlaybackStateCompat.STATE_NONE);
            notifyAdapter(currentSong);
            break;
        case PlaybackStateCompat.STATE_STOPPED:
            pgPlayPauseLayout.setVisibility(View.INVISIBLE);
            btn_play.Pause();
            audioPg.setValue(0);
            if (currentSong != null) {
                currentSong.setPlayState(PlaybackStateCompat.STATE_NONE);
                notifyAdapter(currentSong);
            }
            break;
        case PlaybackStateCompat.STATE_BUFFERING:
            pgPlayPauseLayout.setVisibility(View.VISIBLE);
            if (currentSong != null) {
                currentSong.setPlayState(PlaybackStateCompat.STATE_NONE);
                notifyAdapter(currentSong);
            }
            break;
    }
}
 
Example 16
Source File: MediaEventResponder.java    From Noyze with Apache License 2.0 4 votes vote down vote up
public static Pair<MediaMetadataCompat, PlaybackStateCompat> respond(Context context, Intent intent) {
    if (null == context || null == intent) return null;
    String mAction = intent.getAction();
    Bundle extras = intent.getExtras();
    if (null == extras) extras = Bundle.EMPTY; // In case we've got nothing.
    MediaMetadataCompat.Builder mBuilder = null;
    PlaybackStateCompat.Builder pBuilder = null;

    int state = PlaybackStateCompat.STATE_NONE;
    long position = 0;

    LOGI("MediaEventResponder", mAction + ", extras=" + Utils.bundle2string(intent.getExtras()));
    if (mAction.startsWith("com.amazon.mp3")) {
        mBuilder = new MediaMetadataCompat.Builder();
        pBuilder = new PlaybackStateCompat.Builder();
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, extras.getString("com.amazon.mp3.artist"));
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, extras.getString("com.amazon.mp3.track"));
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, extras.getString("com.amazon.mp3.album"));
        state = (isPlaying(extras.getInt("com.amazon.mp3.playstate")) ?
                PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_STOPPED);
    } else if (mAction.startsWith("com.sonyericsson")) {
        mBuilder = new MediaMetadataCompat.Builder();
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, extras.getString("ARTIST_NAME"));
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, extras.getString("TRACK_NAME"));
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, extras.getString("ALBUM_NAME"));
    } else {
        // This is the default case, standard API check.
        mBuilder = new MediaMetadataCompat.Builder();
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, extras.getString("artist"));
        mBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, extras.getString("album"));
        if (extras.containsKey("title"))
            mBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, extras.getString("title"));
        else if (extras.containsKey("track"))
            mBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, extras.getString("track"));
    }

    // Try the many ways to interpret the play state.
    if (null == pBuilder) {
        pBuilder = new PlaybackStateCompat.Builder();
        String extraKey = null;
        if (extras.containsKey("playstate"))
            extraKey = "playstate";
        else if (extras.containsKey("isPlaying"))
            extraKey = "isPlaying";
        else if (extras.containsKey("playing"))
            extraKey = "playing";
        else if (extras.containsKey("state"))
            extraKey = "state";

        // We still haven't given up, check the action.
        if (TextUtils.isEmpty(extraKey)) {
            boolean bState = false;
            if (mAction.endsWith("endofplayback"))
                bState = false;
            else if (mAction.endsWith("playbackcomplete"))
                bState = false;
            else if (mAction.endsWith("ACTION_PLAYBACK_PAUSE")) // SEMC Legacy
                bState = false;
            else if (mAction.endsWith("ACTION_PAUSED")) // SEMC
                bState = false;
            else if (mAction.endsWith("ACTION_TRACK_STARTED")) // SEMC Legacy
                bState = true;
            else if (mAction.endsWith("ACTION_PLAYBACK_PLAY")) // SEMC
                bState = true;
            state = (bState ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_STOPPED);
        } else {
            state = (extras.getBoolean(extraKey) ? PlaybackStateCompat.STATE_PLAYING : PlaybackStateCompat.STATE_STOPPED);
        }
    }

    // Some extras we might want to use... might.
    if (extras.containsKey("duration"))
        mBuilder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, extras.getLong("duration"));
    if (extras.containsKey("position"))
        position = extras.getLong("position");

    // Attempt to figure out what app is playing music.
    pBuilder.setState(state, position, 1.0f);
    mBuilder.putString(RemoteControlCompat.METADATA_KEY_PACKAGE, packageForAction(mAction));

    // Workaround for Google Play Music... not the best :(
    if (extras.containsKey("previewPlayType") && extras.containsKey("supportsRating") &&
            extras.containsKey("currentContainerId"))
        mBuilder.putString(RemoteControlCompat.METADATA_KEY_PACKAGE, "com.google.android.music");

    // Workaround for Poweramp... should be pretty specific.
    if (extras.containsKey("com.maxmpz.audioplayer.source"))
        mBuilder.putString(RemoteControlCompat.METADATA_KEY_PACKAGE, "com.maxmpz.audioplayer");

    return Pair.create(mBuilder.build(), pBuilder.build());
}
 
Example 17
Source File: AudioPlaybackListener.java    From DMAudioStreamer with Apache License 2.0 4 votes vote down vote up
@Override
public void play(MediaMetaData item) {
    mPlayOnFocusGain = true;
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();
    String mediaId = item.getMediaId();
    boolean mediaHasChanged = !TextUtils.equals(mediaId, mCurrentMediaId);
    if (mediaHasChanged) {
        mCurrentPosition = 0;
        mCurrentMediaId = mediaId;
    }
    if (mState == PlaybackStateCompat.STATE_PAUSED && !mediaHasChanged && mMediaPlayer != null) {
        configMediaPlayerState();
    } else {
        mState = PlaybackStateCompat.STATE_STOPPED;
        relaxResources(false); // release everything except MediaPlayer
        String source = item.getMediaUrl();
        if (source != null) {
            source = source.replaceAll(" ", "%20"); // Escape spaces for URLs
        }
        try {
            createMediaPlayerIfNeeded();
            mState = PlaybackStateCompat.STATE_BUFFERING;
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(source);

            mMediaPlayer.prepareAsync();
            mWifiLock.acquire();

            if (mCallback != null) {
                mCallback.onPlaybackStatusChanged(mState);
            }

        } catch (IOException ex) {
            Logger.e(TAG, ex, "Exception playing song");
            if (mCallback != null) {
                mCallback.onError(ex.getMessage());
            }
        }
    }
}
 
Example 18
Source File: Playback.java    From react-native-streaming-audio-player with MIT License 4 votes vote down vote up
public void playFromUri(Uri uri, Bundle bundle) {
    mPlayOnFocusGain = true;
    tryToGetAudioFocus();
    registerAudioNoisyReceiver();

    mState = PlaybackStateCompat.STATE_STOPPED;
    relaxResources(true);

    try {
        createMediaPlayerIfNeeded();

        mState = PlaybackStateCompat.STATE_BUFFERING;
        mCurrentPosition = 0;

        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setDataSource(uri.toString());

        // Starts preparing the media player in the background. When
        // it's done, it will call our OnPreparedListener (that is,
        // the onPrepared() method on this class, since we set the
        // listener to 'this'). Until the media player is prepared,
        // we *cannot* call start() on it!
        mMediaPlayer.prepareAsync();

        // If we are streaming from the internet, we want to hold a
        // Wifi lock, which prevents the Wifi radio from going to
        // sleep while the song is playing.
        mWifiLock.acquire();

        if (mCallback != null) {
            mCallback.onPlaybackStateChanged(mState);

            MediaMetadataCompat.Builder metaBuilder = new MediaMetadataCompat.Builder();
            metaBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, bundle.getString(MediaMetadataCompat.METADATA_KEY_ARTIST));
            metaBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, bundle.getString(MediaMetadataCompat.METADATA_KEY_TITLE));
            metaBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, bundle.getString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI));
            mCallback.onMediaMetadataChanged(metaBuilder.build());
        }

    } catch (IOException ex) {
        Log.e(TAG, ex +  "Exception playing song");
        if (mCallback != null) {
            mCallback.onError(ex.getMessage());
        }
    }
}
 
Example 19
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
/**
     * Extracts link from youtube video ID, so mediaPlayer can play it
     */
    private void extractUrlAndPlay()
    {
//        LogHelper.e(TAG, "extractUrlAndPlay: extracting url for video id=" + currentVideo.getId());
        final String youtubeLink = "http://youtube.com/watch?v=" + currentVideo.getId();
//        LogHelper.e(TAG, youtubeLink);

        YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this)
        {
            @Override
            public void onUrisAvailable(String videoId, final String videoTitle,
                                        SparseArray<YtFile> ytFiles)
            {
                if (ytFiles != null) {
                    YtFile ytFile = getBestStream(ytFiles);

                    playOnFocusGain = true;
                    currentPosition = 0;
                    tryToGetAudioFocus();
                    registerAudioNoisyReceiver();
                    playState = PlaybackStateCompat.STATE_STOPPED;
                    relaxResources(false); // Release everything except MediaPlayer

                    try {
//                        LogHelper.e(TAG, ytFile.getUrl());
//                        LogHelper.e(TAG, "extractUrlAndPlay: Start playback");

                        createMediaPlayerIfNeeded();

                        playState = PlaybackStateCompat.STATE_BUFFERING;

                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mediaPlayer.setDataSource(ytFile.getUrl());
                        mediaPlayer.setOnPreparedListener(backgroundAudioService);
                        currentVideoTitle = videoTitle;

                        // Starts preparing the media player in the background. When
                        // it's done, it will call our OnPreparedListener (that is,
                        // the onPrepared() method on this class, since we set the
                        // listener to 'this'). Until the media player is prepared,
                        // we *cannot* call start() on it!
                        mediaPlayer.prepareAsync();

                        // If we are streaming from the internet, we want to hold a
                        // Wifi lock, which prevents the Wifi radio from going to
                        // sleep while the song is playing.
                        wifiLock.acquire();
//                            mediaPlayer.start();

//                        if (callback != null) {
//                            callback.onPlaybackStatusChanged(playState);
//                        }
                    } catch (IOException io) {
//                        LogHelper.e(TAG, io, "extractUrlAndPlay: Exception playing song");
                        io.printStackTrace();
                    }
                }
            }
        };
        // Ignore the webm container formatViewCount
//         ytEx.setIncludeWebM(false);
//         ytEx.setParseDashManifest(true);
        // Lets execute the request
        ytEx.execute(youtubeLink);
    }
 
Example 20
Source File: RemoteControlClientLP.java    From Popeens-DSub with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void setPlaybackState(int state, int index, int queueSize) {
	PlaybackStateCompat.Builder builder = new PlaybackStateCompat.Builder();

	int newState = PlaybackStateCompat.STATE_NONE;
	switch(state) {
		case RemoteControlClient.PLAYSTATE_PLAYING:
			newState = PlaybackStateCompat.STATE_PLAYING;
			break;
		case RemoteControlClient.PLAYSTATE_STOPPED:
			newState = PlaybackStateCompat.STATE_STOPPED;
			break;
		case RemoteControlClient.PLAYSTATE_PAUSED:
			newState = PlaybackStateCompat.STATE_PAUSED;
			break;
		case RemoteControlClient.PLAYSTATE_BUFFERING:
			newState = PlaybackStateCompat.STATE_BUFFERING;
			break;
	}

	long position = -1;
	if(state == RemoteControlClient.PLAYSTATE_PLAYING || state == RemoteControlClient.PLAYSTATE_PAUSED) {
		position = downloadService.getPlayerPosition();
	}
	builder.setState(newState, position, 1.0f);
	DownloadFile downloadFile = downloadService.getCurrentPlaying();
	Entry entry = null;
	boolean isSong = true;
	if(downloadFile != null) {
		entry = downloadFile.getSong();
		isSong = entry.isSong();
	}

	builder.setActions(getPlaybackActions(isSong, index, queueSize));

	if(entry != null) {
		addCustomActions(entry, builder);
		builder.setActiveQueueItemId(entry.getId().hashCode());
	}

	PlaybackStateCompat playbackState = builder.build();
	mediaSession.setPlaybackState(playbackState);
	previousState = state;
}