Ten out of ten

News about games by Vatigo

Switching music files in LibGDX

May 092014

undefined

This post is mostly a memo for myself but I figured maybe there are other newbies like me out there that could find it useful ;)

Music objects in LibGDX are quite huge so ideally we only want one in the memory - the song that's currently playing. We'd also like to have a different song for every level so that means we're going to have to load and unload music files as necessary.

To achieve that, I made a class called AudioPlayer which contains static methods for playing music and switching music files. It also handles sound effects, but that's not the focus of this post so I'll ignore it.

If you need many different songs, it would be better to pass a path to the song file as a parameter of the method, but since I only needed 3 songs I placed the paths directly inside the method and I load the appropriate file using the value of the integer parameter.

public static void setSong(int i) {
//nothing to do, the song we want to load is already loaded if (currentSong == i) return; if (levelSong!=null){ //a different song is loaded levelSong.stop(); //stop it levelSong.dispose(); //dispose it levelSong = null; }

//load the appropriate file switch (i){ case 1: levelSong = Gdx.audio.newMusic(Gdx.files.internal("data/music/1.mp3")); break; case 2: levelSong = Gdx.audio.newMusic(Gdx.files.internal("data/music/2.mp3")); break; case 3: levelSong = Gdx.audio.newMusic(Gdx.files.internal("data/music/3.mp3")); break; }

//remember the song we loaded currentSong = i; }

To use it, when the level loads I just call for example:

AudioPlayer.setSong(1);
AudioPlayer.playMusic();

That's all there is to it.

The playMusic method just calls levelSong.play();

Atom

Copyright 2014 Vatigo Games