Search code examples
androidaudiomedia-player

Android MediaPlayer getCurrentPosition() causes audio stutter


I'm using a SeekBar to display the progress of an audio file and for seeking to a certain time. For updating I use a Runnable which calls getCurrentPosition() on a MediaPlayer every second or so. Every time that happens there is a small amount of lag in the audio. Since I call it often, I get very noticeable stuttering while playing something. If it's relevant, I'm using setAudioStreamType(AudioManager.STREAM_MUSIC) and the file format is mp4 whith AAC audio (no video) and I'm using Android 2.3.4. Is there a way to get good audio with getCurrentPosition(), or do I have to implement my own progress calculations?

The Runnable:

private Runnable mUpdateTask = new Runnable(){

    @Override
    public void run() {
        mSeekBar.setProgress((int) (mPlayer.getCurrentPosition() * 100 / mArrayAdapter.getRecording(mPlayingId).mDuration));
        mHandler.postDelayed(mUpdateTask, 999);
    }
};

Solution

  • I use this method to caluclate progress'

    public static int getProgressPercentage(long currentDuration,
                long totalDuration) {
            Double percentage = (double) 0;
    
            long currentSeconds = (int) (currentDuration / 1000);
            long totalSeconds = (int) (totalDuration / 1000);
    
            // calculating percentage
            percentage = (((double) currentSeconds) / totalSeconds) * 100;
    
            // return percentage
            return percentage.intValue();
        }
    

    Note: mPlayer.getCurrentPosition() is not accurate. There are some bugs reported. I had problem that current position was higher than totalDuration.