How to control MediaPlayer launch delay?

First, my goal is to play sound on devices with the same start time. Even a delay of 100 ms is very important to me . Therefore, I have to be very careful in this delay control.

Suppose I synchronize all my devices using the network time protocol. I connect 0.tr.pool.ntp.org and with added delays I have the following data:

  • Your system time: 14: 45: 50.255000 (a) On my device
  • NTP Time: 14: 46: 01.255000 (b)

It is working fine. I have a BroadcastReceiver class as an alarm receiver. Again, for example, I will play the sound in the format 14: 50: 00.000, and for AlarmManager - ((14: 50: 00.000) - (a - b)) to synchronize with the NTP server.

So far, everything is fine. My problem starts with a delay of almost 250 ms (c) on BroadcastReceiver. This delay never goes 1000ms ++. I solved this problem by changing the alarm time to ((14: 50: 00.000) - (a - b) - 1000 ms) and then on the BroadcastReceiver add a delay (1000 ms - c) . This is still a big thank you to God :)

The final step is to play the sound, it is very simple to add this code block:

MediaPlayer player = MediaPlayer.create(getBaseContext(), R.raw.mysound); 
player.setOnCompletionListener(new OnCompletionListener() {
    public void onCompletion(MediaPlayer player) {
        player.release();
    }
});
player.start();

, ? , . :

private void synchronizeMediaPlayer(){
    long startMs = new Date().getTime();
    MediaPlayer player = MediaPlayer.create(getBaseContext(), R.raw.mysound); 
    player.setOnCompletionListener(new OnCompletionListener() {
        public void onCompletion(MediaPlayer player) {
            player.release();
        }
    });
    player.start();
    long finishMs = new Date().getTime();
    delayPlayer = finishMs - startMs; // this is static variable for using in any class
    player.stop();
    player.release();
}

Ok. , delayPlayer 1000ms ++. , , ((14: 50: 00.000) - (a - b) - 1000 - 1000 ), (1000 - delayPlayer) . , .

: , , (, 50 -250 ) . . , - delayPlayer. , ( , ..). , , . 1 , , . ; 150 , 1 300 .

MediaPlayer? , .

: . ...

+4

All Articles