Search code examples
javaandroidlibgdx

Libgdx: Lags in soundtrack looping


I'm having trouble with music looping in libgdx. I know a simmilair topic was here before, but it didn't help me at all. The thing is that when you go to main menu in my game (link) the sound of rain is looped. Unfortunately, there is a short moment of silence between each play and I don't know why - you can download the game and see what I mean. I'm already using .ogg format, so the solution from the other topic I found here didn't really help.

If I play this sound in a loop in Audacity, it works perfectly.

Here is my code (I don't think it'll help, though):

rainSoundtrack = Gdx.audio.newMusic(Gdx.files.internal("soundtrack.ogg"));
rainSoundtrack.setLooping(true);

Solution

  • The problem is the way libGDX handles Music. I will quote a badlogic post on GitHub issue 1654.

    the Android situation is a bit more complicated and sad. On Android we use the system facilities to playback audio, namely MediaPlayer. This pieces of Android software uses device dependend drivers under the hood (audio drivers, custom codec implementations, etc.). This means that we are at the mercy of hardware vendors like Samsung and their driver implementations.

    The problem is not bound only to libGDX, it is Android issue 18756.

    Solution

    Your soundtrack is short and small in term of memory size so using libGDX sound is actually better in this case and it is free of this gap bug.

    Music -> long and big files, not loaded into memory

    Sound -> short and small files, loaded into memory

    Use Sound class and loop it. Example:

    long id;
    ...
    public void create() {
        music = Gdx.audio.newSound(Gdx.files.internal("soundtrack.ogg"));
        id = music.loop(); //Sound may not be ready here!
    }
    
    public void render() {
        if(id == -1)
            id = music.loop();
    }