Pause exoplayer by Default and response to the play/pause button - android

After loading a video, it starts to play.
I want the video to be paused for the very first time after loading. If the user clicks on the resume button it must start to play. How can I achieve this for exoplayer2.ui.PlayerView?

I want the video to be paused for the very first time after loading
You can use player.setPlayWhenReady(false); when you init your Player.
If the user clicks on the resume button it must start to play.
You can add a ControlDispatcher in your PlayView by calling setControlDispatcher(#Nullable ControlDispatcher controlDispatcher) method, like playerView.setControlDispatcher(new MyDefaultControlDispatcher());
The class MyDefaultControlDispatcher is my Custom ControlDispatcher, as below:
private class MyDefaultControlDispatcher extends DefaultControlDispatcher {
#Override
public boolean dispatchSetPlayWhenReady(Player player, boolean playWhenReady) {
super.dispatchSetPlayWhenReady(player, playWhenReady);
if (playWhenReady && player.getPlaybackState() == Player.STATE_READY) {
player.setPlayWhenReady(true);
}
return true;
}
}
You can inherit the DefaultControlDispatcher to Override your favorite method , like dispatchSetPlayWhenReady, OR implement the interface ControlDispatcher.
The method dispatchSetPlayWhenReady will get your click event on the play/stop button in your PlayView. You can verify it in your PlayerControlView's OnClick method. I will show your picture as below:
PS: Like #ahmedaljubair has mentioned that the method setPlayWhenReady only work when the player is in the ready state. So, you need check the player's state when you call the setPlayWhenReady method to pause and resume your player.

Related

How to add resume in amazon polly's text to speech in android?

I am using Amazon Polly , and I want to resume pronounced speech where it was paused but it starts from beginning whenever i tried to resume. I set source in media player as follows
mediaPlayer.setDataSource(presignedSynthesizeSpeechUrl.toString());
The code I tried to use pause and resume is as follows,
playPauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pauseVal){
mediaPlayer.seekTo(length);
mediaPlayer.start();
pauseVal = false;
}else{
mediaPlayer.pause();
length= mediaPlayer.getCurrentPosition();
pauseVal = true;
}
}
});
I am stuck here , can't move further with resume functionality. I will be thankful if any of you help.
Media player doesn't support resume functionality for passed URL . since I was using webview so I just passed that URL to Audio tag which supports resume functionality.
https://www.w3schools.com/html/html5_audio.asp

Detect pause/resume in ExoPlayer

I searched two days for this question in github but i can't find true answer . I want example for detecting pause / resume in ExoPlayer > 2.x .
Any one can give me an example ? I checked onPlayerStateChanged and problem not solved .
onPlayerStateChanged : STATE_BUFFERING
onPlayerStateChanged : STATE_READY
I just got this log from onPlayerStateChanged and this is not called in all times !
EDIT---
Please refer to the Player.isPlaying() method which provides this as an API.
"Rather than having to check these properties individually, Player.isPlaying can be called."
https://exoplayer.dev/listening-to-player-events.html#playback-state-changes
--- EDIT END
You need to check playWhenReady with a Player.EventListener. The Playback states of ExoPlayer are independent from the player being paused or not:
player.addListener(new Player.DefaultEventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playWhenReady && playbackState == Player.STATE_READY) {
// media actually playing
} else if (playWhenReady) {
// might be idle (plays after prepare()),
// buffering (plays when data available)
// or ended (plays when seek away from end)
} else {
// player paused in any state
}
}
});
To play/pause the player ExoPlayer provides
player.setPlayWhenReady(boolean)
The sequence of playback states with ExoPlayer with a media file which never stalls to rebuffer is once in each of the four states and does not express play/paused:
Player.STATE_IDLE;
Player.STATE_BUFFERING;
Player.STATE_READY;
Player.STATE_ENDED;
Each time the player needs to buffer it goes:
Player.STATE_READY;
Player.STATE_BUFFERING;
Player.STATE_READY;
Setting playWhenReady does not affect the state.
All together your media is actually playing when
playWhenReady && playbackState == Player.STATE_READY
It plays when ready. :)
You can use this function:
public boolean isPlaying() {
return exoPlayer.getPlaybackState() == Player.STATE_READY && exoPlayer.getPlayWhenReady();
}
It must be that since the other answers were posted, a new method has been provided in Player.EventListener. [EDIT: Now it is Player.Listener, as Player.EventListener has been deprecated]. This works well for me:
override fun onIsPlayingChanged(isPlaying: Boolean) {
// your code here
}
If isPlaying is false, it is paused, otherwise playing.
I had the same requirement to detect the click event of exoplayer play/pause button. Above answers were mainly talking about the state not
about the button click event.
This is what I did to detect the Play/Pause button click, works perfect.
Step 1: Create custom control dispatcher class and override the method dispatchSetPlayWhenReady
class PlayerControlDispatcher : DefaultControlDispatcher() {
override fun dispatchSetPlayWhenReady(player: Player?, playWhenReady: Boolean): Boolean {
if(playWhenReady) {
// Play button clicked
} else {
// Paused button clicked
}
return super.dispatchSetPlayWhenReady(player, playWhenReady)
}
}
Step 2: Set the custom control dispatcher class PlayerControlDispatcher into the the player view.
playerView.setControlDispatcher(PlayerControlDispatcher())
Where playerView is an instance of com.google.android.exoplayer2.ui.PlayerView which we declare in our layout file.
Kotlin 2020 solution approach UPDATE
Events such as changes in state and playback errors are reported to registered Player.EventListener instances.
Player.EventListener has empty default methods, so you only need to implement the methods you’re interested in.
First your class, say your activity, has to conform to the Player.EventListener interface.
Then you override the onIsPlayingChanged method, on the class. Outside onCreate method...
Add the listener to your player instance:
// Adding player listener for tracking events
player?.addListener(this)
You can check if the player is playing (i.e. the position is advancing) with Player.isPlaying:
//Listening to player events
override fun onIsPlayingChanged(isPlaying: Boolean){
if (isPlaying) {
// Active playback.
} else {
// Not playing because playback is paused, ended, suppressed, or the player
// is buffering, stopped or failed. Check player.getPlaybackState,
// player.getPlayWhenReady, player.getPlaybackError and
// player.getPlaybackSuppressionReason for details.
}
}
That's it. Very simple.
You can use exoplayer.getPlayWhenReady() to check whether the player is currently in a pause state or playing state.
I think the callback:
fun onPlayWhenReadyChanged(playWhenReady: Boolean, reason: Int)
From the Player.Listener
With version 2.16.1, I use this code:
exoPlayer.addListener(object : Player.Listener {
override fun onIsPlayingChanged(isPlaying: Boolean) {
if (isPlaying){
videoIsPlaying()
}
}
})
Please try below code snipped. The player listener(onPlayerStateChanged) isn't good to observe play / pause action its called multiple time and also invoke while player configuring.
videoView.setControlDispatcher(object : DefaultControlDispatcher() {
override fun dispatchSetPlayWhenReady(player: Player, playWhenReady: Boolean): Boolean {
if (playWhenReady)
// Tap on Play button
else
// Tap on Pause button
return super.dispatchSetPlayWhenReady(player, playWhenReady)
}
})
for kotlin
private fun ExoPlayer.isPlaying() =
playbackState == Player.STATE_READY && playWhenReady

ExoPlayer , Loop Ended/ Started listener for LoopingMediaSource

I am using ExoPlayer for playing video in loop, but before source video is started each loop I need to reset some states of my Layout. I know ExoPlayer is calling onPlayerStateChanged with ExoPlayer.STATE_ENDED paramter when video is ended for usual MediaSources, but it is not called for LoopingMediaSource.
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == ExoPlayer.STATE_ENDED) {
showControls();
resetLayoutStates(); //I need it here, even in LoopingMediaSource
}
updateButtonVisibilities();
}
Does the Exoplayer have any Callback when Source is restarted or ended in loop ? Or does it have any workaround for my situation ?
You can detect that a video loops when the media item changes. This callback will be fired at the end of the media item and give you the new item to play even if that's the same when repeat mode is ONE. You can detect that with the reason parameter that tells you why the media changed (either naturally, seeking or looping):
override fun onMediaItemTransition(mediaItem: MediaItem?, reason: Int) {
super.onMediaItemTransition(mediaItem, reason)
if (reason == Player.MEDIA_ITEM_TRANSITION_REASON_REPEAT) {
// Reset your state
}
}
You may want to assert that it's the right media item with the given mediaItem argument. Especially since it will behave differently whether your repeat mode is ONE or ALL (the media item will be the same for ONE while the first or last item of your timeline for ALL).

Resume MediaPlayer after pressing Home Button

I have a MediaPlayer that streams music in the background, when I press the home button the music stops, which what I want, but when I resume back to the application, the music is not there anymore. And when the current track ends, it doesn't loop.
My code is the following:
MediaPlayer backgroundMusic;
int length = 0;
//play background music
backgroundMusic = MediaPlayer.create(MainActivity.this, R.raw.background_music);
backgroundMusic.start();
backgroundMusic.setLooping(true);
#Override
protected void onPause() {
super.onPause();
if(backgroundMusic.isPlaying()){
backgroundMusic.pause();
length = backgroundMusic.getCurrentPosition();
}else{
return;
}
}
public void onPrepared(MediaPlayer backgroundMusic){
backgroundMusic.start();
backgroundMusic.seekTo(length);
}
How can I resume the music from where it stopped, when I press the Home Button, and Also make the music loop.
Thanks in advance.
Try to implement your code with service class if you want your player to play even in background or if you want to store the position save your data in static variable in onpause and restore it onResume of your Activity.
Preserve position of playing in shared preferences and not in local variable

Android event listeners for audio

I'm playing around with Android to learn the API and I'm trying to code an activity which can listen for changes in audio events. For example, the activity I created plays a random ringtone when you press a button. The button displays a text saying "Random Ringtone", but when you press the button it says "Stop" and pressing it will, of course, stop playing the ringtone.
However, the problem is that when the ringtone stops playing on its own, the button still says "stop".
I've looked around to try to find an event listener that could listen for when the ringtone stops playing, but I can't seem to find one. I've seen some info out there about creating your own listeners, but I'm not interested in doing that (a little advanced for me right now).
Does an event listener of this type exist?
I may be wrong but I think the only audio class which raises an event when it finishes playing is the MediaPlayer class. Something like this should work...
public class MyActivity extends Activity
implements MediaPlayer.OnCompletionListener {
MediaPlayer player = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
player = new MediaPlayer();
player.setOnCompletionListener(this);
...
}
#Override
public void onCompletion(MediaPlayer mp) {
// Called when playback is complete
...
}
}

Categories

Resources