Search code examples
javaaudiolibgdxdispose

Using "dispose()" on a Music object inside its "OnCompletionListener()"?


It seemed like a good idea to have a Music object dispose() of itself when its song ended. Just call individual_Music.dispose() in the Music object's OnCompletionListener(), right? Well, that has not worked so well.

I declare the following earlier in the file:

private Music musicMoment = Gdx.audio.newMusic( Gdx.files.internal( "music/blank.ogg" ) );

The following method sets up the listener:

void music_Setup_for_One_File() {

    musicMoment.setVolume( 0.6f );

    musicMoment.setOnCompletionListener( new Music.OnCompletionListener() {

        @Override
        public void onCompletion( Music musicTest ) {

            musicMoment.dispose();
            musicTest.dispose();

            System.out.println( "TEST test Moo!!!!");

        }

    });

}

I use the following method to see if musicMoment is null or not when the program comes to a close:

final void dispose_of_Single_Music_Song_Before_It_Finishes() {

    boolean test = false;


    if ( musicMoment != null ) {

        musicMoment.dispose();
        System.out.println( "'musicMoment' song disposed of from memory." );

    } else {

        System.out.println( "There is no need to clear 'musicMoment'.  It is already null." );

    }

}

The code above always shows the Music object, musicMoment, as not null. The software may run several seconds, and even though " blank.ogg " lasts less than a second, this seems to stay true each time. Calling dispose() outside of the listener works fine, so 'musicMoment' appears null then.

How do I properly dispose of the song when it ends, if dispose() does not work inside the listener?


Solution

  • dispose() will not clear reference of any object. If you don't have reference of any object that might be cleared from heap memory when garbage collector run.

    According to doc, Heavy resources like Images and sound effects managed by native drivers instead of Java garbage collector.

    Those resources need to be manually disposed when your resource no longer needed. All those resources implement a common interface Disposable.

    Failure to dispose resources will lead to severe memory leaks!.

    Resources should be disposed of as soon as they are no longer needed, freeing up memory associated with them. Accessing a disposed resource will result in undefined errors, so make sure to clear out all references you have to a disposed resource.