Search code examples
libgdx

Music cannot play again after dispose


Im trying to build a static AudioManager which is able to play any music with only referring one instance. However, the same music cannot play again after I dispose it from the instance.

The AudioManager works when run on desktop, but fail when run on android device.

The main function from static AudioManager class:

Music music = null;
public static Music playMusic(String musicName){
    if (music!=null){
        music.stop();
        music.dispose();
    }

    music = assetManager.get("music/"+musicName,Music.class);
    music.setLooping(true);
    music.play();
    currentMusicName = musicName;
    MyDebugger.d("new music !");
    return music;
}

The changing from music_A to music_B works, but reusing music_A does not play any music with no errors. (in android device)

Any help please.


Solution

  • You are disposing your music and then trying to reuse the same music instance when you use assetManager.get().

    When you use AssetManager to load an asset, you should not be disposing it. You should be unloading it. That also means you cannot reuse it after unloading it. You need to load a new copy.

    Music music = null;
    public static Music playMusic(String musicName)
    {
    
        if (music!=null){
            music.stop();
            assetManager.unload(music);
        }
    
        assetManager.load("music/"+musicName,Music.class);
        assetManager.finishLoading();
        music = assetManager.get("music/"+musicName,Music.class);
        music.setLooping(true);
        music.play();
        currentMusicName = musicName;
        return music;
    }
    

    But since you are only ever loading one music instance at a time (judging from your use of the static method), it might be easier not to use the asset manager at all for it.

    Be careful using static for anything involving Disposables. Don't forget to dispose it when the game's dispose() is called.