Skip to content Skip to sidebar Skip to footer

Binding MediaPlayer To Be Played At A Specific Time

When using MediaPlayer, I noticed that whenever my phone stucks, the MediaPlayer glitches and then continues playing from the position in the audio it glitched. This is bad for my

Solution 1:

You will need to use possibly mp.getDuration(); and/or mp.getCurrentPosition(); although it's impossible to know exactly what you mean by "I need the audio to be played exactly(~) at the time it was supposed to be played."

Something like this should get you started:

 int a = (mp.getCurrentPosition() + b);

Solution 2:

Thanks for the answer Mike. but unfortunately this won't help me.

Let's say that I asked MediaPlayer to start playing a song of length 3:45 at 00:00.
At 01:00 I started using the phone's resources, due to the heavy usage my phone glitched making MediaPlayer pause for 2 seconds.

Time:

00:00-01:00 - I heard the audio at 00:00-01:00
01:00-01:02 - I heard silence because the phone glitched
01:02-03:47 - I heard the audio at 01:00-03:45 with 2 second time skew

Now from what I understood MediaPlayer is a bad choice of usage on this problem domain, since MediaPlayer provides a high level API.
I am currently experimenting with the AudioTrack class which should provide me with what I need:

//Creating a new audio track
AudioTrack audioTrack = new AudioTrack(...)

//Get start time
long start = System.currentTimeMillis();

// loop until finished
for (...) {
    // Get time in song
    long now = System.currentTimeMillis();
    long nowInSong = now - start;
    // get a buffer from the song at time nowInSong with a length of 1 second
    byte[] b = getAudioBuffer(nowInSong);
    // play 1 second of music
    audioTrack.write(b, 0, b.length);
    // remove any unplayed data
    audioTrack.flush();
}

Now if I glitch I only glitch for 1 second and then I correct myself by playing the right audio at the right time!

NOTE

I haven't tested this code but it seems like the right way to do it. If it will actually work I will update this post again.

P.S. seeking in MediaPlayer is: 1. A heavy operation that will surely delay my music (every millisecond counts here) 2. Is not thread safe and cannot be used from multiple threads (seeks, starts etc...)


Post a Comment for "Binding MediaPlayer To Be Played At A Specific Time"