简体   繁体   中英

How to prevent MediaPlayer from getting started when setPlaybackParams() is called using Java in Android Studio?

In my project I need to set the playback params before the MediaPlayer is started ( MediaPlayer will start when user clicks a Button ). But when I set playback params using the code given below, the MediaPlayer automatically gets started.

mediaPlayer.setPlaybackParams(mediaPlayer.getPlaybackParams().setSpeed(1.5f));

Now, how would I prevent it from getting started?

(You can say, I might just set the params when button is clicked, but it won't work as I have several MediaPlayer s to set params.)

According to MediaPlayer s doc:

public void setPlaybackParams (PlaybackParams params)

Sets playback rate using PlaybackParams. The object sets its internal PlaybackParams to the input, except that the object remembers previous speed when input speed is zero. This allows the object to resume at previous speed when start() is called. Calling it before the object is prepared does not change the object state . After the object is prepared, calling it with zero speed is equivalent to calling pause(). After the object is prepared, calling it with non-zero speed is equivalent to calling start() .

I suspect you call mediaPlayer.prepare() before you set the params or you have used mediaPlayer.create() (which is equivalent to call mediaPlayer.setDataSource() and mediaPlayer.prepare() both at the same time. So, you indirectly called mediaPlayer.prepare() ), in which case the player will start playing when the params are set, exactly as described in the documentations.

So, use mediaPlayer.setDataSource() and then set playback params (so that it doesn't automatically start the mediaPlayer ). After that call mediaPlayer.prepare() before calling mediaPlayer.start() .

If you need to change speed while not restarting, you could check playing status before then use this info to stop playing just after changing speed: mediaPlayer is your Mediaplayer instance, speed is your value for speed

var isCurrentlyPlaying:Boolean=mediaPlayer!!.isPlaying
mediaPlayer!!.setPlaybackParams(mediaPlayer!!.getPlaybackParams().setSpeed(speed))
if (!isCurrentlyPlaying) {
    mediaPlayer!!.pause()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM