karthiks karthiks - 11 months ago 69
Android Question

Play audio between points A and B

How to set From and To Timestamp markers and play media between these two points of an audio file? I don't see listener API for MediaPlayer in Android. Wondering how I can go about achieving this?

My situation is like this:
Break audio file into many such parts and let user interactively play/replay select portions of it as he wishes.

For instance, let's assume a small audio file is broken into 3 parts (A---B---C---D), namely, AB, BC, and CD. The user selects part BC and opts to play. The audio then plays starting from point B and stops when it reaches point C. The user may play again part BC or choose to move on to the next part.

While its easier to decide to figure out the starting point and use

API, how is it that I can make the audio stop at the end point? What is the best way forward for this?

Your help is much appreciated.

Answer Source

The way I went about implementing this is as below:

private MediaPlayer mediaPlayer;
private Runnable runnable = new Runnable() {
    public void run() {

private void play(int start, int duration) {
    handler.postDelayed(runnable, duration);

I've copied the key portion of the code relevant for this context. While I did this, I'm not particularly happy with this implementation because this is still not accurate.

I was looking to see if there is someone who used an alternative API to achieve accuracy for this, may be by using Android's AudioTrack API or something like that.

Looks like this is the best alternative available for now, to the best of my knowledge. I shall update this post, should I find a better way and until then, I hope this serves you well as much as it has served me. Cheers!