Search code examples
androidandroid-mediaplayerfadeinfadeoutpause

During crossfading MediaPlayer player pauses for while on some devices mostly on Oreo and Pie


I want crossfading effect when one song is about to end and other starts.I have used below code for crossFading between audio and it works fine on most of the devices but it is not working on some samsung devices running on Oreo and one plus 6. Their is very small pause as soon as second media player starts playing next song. Thanks in advance.

private void crossFade() {
    fadeOut(musicPlayer, CROSSFADE_DURATION);
    fadeIn(musicPlayer2, CROSSFADE_DURATION);
}

public void fadeOut(final MediaPlayer _player, final int duration) {
    final float deviceVolume = getDeviceVolume();
    final Handler h = new Handler();
    h.postDelayed(new Runnable() {
        private float time = duration;
        private float volume = 0.0f;

        @Override
        public void run() {               
            // can call h again after work!
            time -= 100;
            volume = (deviceVolume * time) / duration;
            _player.setVolume(volume, volume);
            if (time > 0)
                h.postDelayed(this, 100);
            else {
                _player.stop();
                _player.release();
            }
        }
    }, 100); // delay (takes millis)


}

public void fadeIn(final MediaPlayer _player, final int duration) {
    final float deviceVolume = getDeviceVolume();
    final Handler h = new Handler();
    h.postDelayed(new Runnable() {
        private float time = 0.0f;
        private float volume = 0.0f;

        @Override
        public void run() {
            if (!_player.isPlaying())
                _player.start();
            // can call h again after work!
            time += 100;
            volume = (deviceVolume * time) / duration;
            _player.setVolume(volume, volume);
            if (time < duration)
                h.postDelayed(this, 100);
        }
    }, 100); // delay (takes millis)

}

Solution

  • Finally I solved this issue by my own. Actualy MediaPlayer has this issue and its been reported to google since long ago but still not resolved(https://issuetracker.google.com/issues/36931073) so we can do nothing about it. So I used Exoplayer for playing audio and it works very smoothly without any pause.