I'm using libGDX and face the problem that background music does not flawlessly loop on various Android devices (Nexus 7 running Lollipop for example). Whenever the track loops (i.e. jumps from the end to the start) a clearly noticeable gap is hearable. Now I wonder how the background music can be played in a loop without the disturbing gap?
I've already tried various approaches like:
- Ensuring the number of Samples in the track are an exact multiple of the tracks sample rate (as mentioned somewhere here on SO).
- Various audio formats like .ogg, .m4a, .mp3 and .wav (.ogg seems to be the solution of choice here at SO, but unfortunately it does not work in my case).
- Used Androids MediaPlayer with setLooping(true) instead of libGDX Music class.
Used Androids MediaPlayer.setNextMediaPlayer(). The code looks like the following, and it plays the two tracks without a gap in between, but unfortunately, as soon as the second MediaPlayer finishes, the first does not start again!
/* initialization */ afd = context.getAssets().openFd(filename); firstBackgroundMusic.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); firstBackgroundMusic.prepare(); firstBackgroundMusic.setOnCompletionListener(this); secondBackgroundMusic.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); secondBackgroundMusic.prepare(); secondBackgroundMusic.setOnCompletionListener(this); firstBackgroundMusic.setNextMediaPlayer(secondBackgroundMusic); secondBackgroundMusic.setNextMediaPlayer(firstBackgroundMusic); firstBackgroundMusic.start(); @Override public void onCompletion(MediaPlayer mp) { mp.stop(); try { mp.prepare(); } catch (IOException e) { e.printStackTrace(); } }
Any ideas what's wrong with the code snippet?