Search code examples
javaandroidaudioandroid-mediaplayer

Android MediaPlayer Sound Delay


So I am working with the Android MediaPlayer and I seem to have run into a very odd problem. I am making the MediaPlayer play a sound at decreasing intervals. So as time goes on, the amount of time between each sound is decreasing. The sound in question is 0.05 seconds long and the shortest delay between sounds is 0.5 seconds. I have the logcat displaying a message about how long the delay is and it also displays a message when each tick is played. However, when each tick should be played, according to the logcat, it skips over a tick randomly. At other points it also plays a bunch of ticks in one jumbled mess. I'm not really sure what could be causing this and any help is appreciated. The code is below and I can post the logcat if need be.

private Runnable timerRunnable = new Runnable() {
    @Override
    public void run() {
        long millis = System.currentTimeMillis() - startTime;
        int trueSeconds = (int) millis / 1000;
        double seconds = (double) (millis / 1000);
        int minutes = trueSeconds / 60;

        Log.d("Tick Timing", "Delay: " + delay);

        if(lastRun == 0)
            lastRun = System.currentTimeMillis();

        if((System.currentTimeMillis() - startTime) >50000)
            delay = 500;

        else if(System.currentTimeMillis() - lastRun > delay){
            lastRun = System.currentTimeMillis();

            delay /= 1.075;

            if(phaseOne) {
                Log.d("Tick Timing", "Tick One Played");
                tickOne.start();
                phaseOne = false;
            }

            else {
                Log.d("Tick Timing", "Tick Two Played");
                tickTwo.start();
                phaseOne = true;
            }
        }

        timerTextView.setText(minutes + ":" + seconds);

        timerHandler.postDelayed(this, 1);
    }
};`

Solution

  • The problem seems to come from the delay value you give the timerHandler.postDelay() method.

    You give 1 millisecond, causing your Runnable and sounds being started too quickly.

    Try with 500 milliseconds instead.