I am able to play an mp3 file using android's MediaPlayer object. But I would like to play between a range of milliseconds for example between 30000 ms to 40000 ms ( 10 seconds only ). How can I achieve this?
Currently the following code is what I have,
private MediaPlayer mPlayer;
public void play() {
try {
mPlayer = MediaPlayer.create(getApplicationContext(), R.raw.mp3_file);
if (mPlayer != null) {
int currentPosition = mPlayer.getCurrentPosition();
if (currentPosition + 30000 <= mPlayer.getDuration()) {
mPlayer.seekTo(currentPosition + 30000);
} else {
mPlayer.seekTo(mPlayer.getDuration());
}
mPlayer.start();
}
}
catch(Exception e) {
}
}
Any help is greatly appreciated. Thank you!
The best approach is to use a Handler to time the stopping of the playback. Start the player and then use the Handler's
postDelayed
to schedule the execution of aRunnable
that will stop the player. You should also start the player only after the initial seek completes. Something like this:Note also that the
MediaPlayer.create
method you are using returns a MediaPlayer that has already been prepared andprepare
should not be called again like you are doing in your code.on the screen. I also added a call torelease()
when the activity exits.Also, if you want to update the UI when the seek completes, be aware that this method is usually called from a non-UI thread. You will have to use the handler to post any UI-related actions.
I'm copied this from: Android: How to stop media (mp3) in playing when specific milliseconds come?
You can use the method:
to obtain the current time in milSeconds maybe inside a Handler that runs every 1000 milSeconds and tests to see:
Dont forget to release the media file when you're done using it: