javaaudiolibgdxaudio-playerandroid-music-player

Overlapping music in a Java game with LibGDX implementation


I am having a problem in with this part of the code, I am creating a very simple game in Java with the implementation of LibGDX. I have three different game states that are handled in three different classes:

They all work perfectly except for one thing. The music that I have inserted and that is created in the StateCreation should start over, when the player gets to the gameover and the state changes the mode to start over or go back to the menu. This does not happen and the music overlaps

public class GameBarbo extends ApplicationAdapter {                                                  
//impostazioni base dell'applicazione
public static final int WIDTH = 480;
public static final int HEIGHT = 800;

public static final String TITLE = "Cavaliere";
private GameStateManager gsm = new GameStateManager();
private SpriteBatch batch;
private Music music;

@Override
public void create () {
    batch = new SpriteBatch();
    music = Gdx.audio.newMusic(Gdx.files.internal("sound.mp3"));
    music.setVolume(0.1f);
    music.play();
    Gdx.gl.glClearColor(1, 0, 0, 1);
    gsm.push(new MenuState(gsm));
}

@Override
public void render () {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    gsm.update(Gdx.graphics.getDeltaTime());
    gsm.render(batch);
}

@Override
public void dispose() {
    super.dispose();
    music.dispose();
}
}

Solution

  • You code looks very much like what I found in this guide (though they don't include super.dispose().)

    Is it possible that when your game state changes, the dispose() method does not execute? I haven't used libgdx in ages, but it could be the case that dispose() only executes when you exit the program.

    I see from this wiki that the Music class has a stop() method. Perhaps that needs to be called directly when the game ends. But IDK if stopping the file and executing a reload for another iteration is asking for a memory leak or not.

    Hopefully someone with more experience will answer, but maybe these thoughts will help you figure something out in the meantime.