Take your skills to the next level with these bite-sized tutorials!

Playing Music in SGDK


Playing music in SGDK might actually be a lot easier than you think. So let’s quickly look at how it works and create ourselves a little disco, what do you say? Create a new SGDK project and let’s go!

Getting The Groove

First of all we gotta get ourselves some music to play. You can of course compose your own, using a tool like Deflemask, but for the sake of this tutorial we’ll just grab a song from another game. There are many websites out there that archive old chiptune music, including of course music for the Mega Drive. But here is the first thing that you have to watch out for.

Mega Drive music comes in different formats, like .gym and others. SGDK only supports files in VGM, XGM or XGC formats.

So go ahead and grab yourself a .vgm file (or one of the others), then stick it in the resources folder of your project. (If you don’t have .vgm files sitting around and can’t find any online, then SGDK actually comes with some. Check out the sample\xgmplayer\res folder in your main SGDK folder!)

Next we’ll import the music file by adding it to our resources file, probably called resources.res. Add the following line to import the music file:

XGM track1 "musicfile.vgm"

You’ll of course have to change musicfile.vgm to whatever the name of your music file is. You can also change track1 to whatever you want, I’m just keeping things neutral here.

Lay It On Me

Now that we’ve got the music loaded and ready, it’s time to spin up that turntable! And that’s a very quick process, as playing music in SGDK actually only takes two lines of code. Add them to your main() function:

XGM_setLoopNumber(-1);
XGM_startPlay(&track1);

As the name implies, XGM_setLoopNumber sets how often a track should loop. A value of -1 means “infinitely” (but actually just 255 times), a value of 0 will only play a track once. With 1 it would play the track once and then loop it one more time, 2 would play the track a total of three times, and so on.

And XGM_startPlay, well…that plays the music you specify! So if you compile and run the game now, you should be hearing your track.

Pause, Resume and Disco!

That was simple enough, but let’s go a little step further just for fun. First, add a new variable to the top of your main.c file:

bool paused = FALSE;

Then, directly below it, create an array of colors for a little disco light effect:

u16 colors[6] = {
    RGB24_TO_VDPCOLOR(0xFF0000),
    RGB24_TO_VDPCOLOR(0xFFFF00),
    RGB24_TO_VDPCOLOR(0x00FF00),
    RGB24_TO_VDPCOLOR(0x00FFFF),
    RGB24_TO_VDPCOLOR(0x0000FF),
    RGB24_TO_VDPCOLOR(0xFF00FF)
};

You can of course pick any colors you want, I just went with some very simple ones.

Finally, create a joypad callback so we can control the playback of our music a little. This is what the whole thing looks like:

void myJoyHandler(u16 joy, u16 changed, u16 state){
    if(changed & state & BUTTON_START){
        if(paused == FALSE){
            XGM_pausePlay();
            paused = TRUE;
        } else{
            XGM_resumePlay();
            paused = FALSE;
        }
    }
}

The code should be rather self-explanatory. If we press START on the joypad, the music will either pause or resume, depending on whether it’s already playing or not. SGDK gives us the XGM_pausePlay() and XGM_resumePlay() functions to easily accomplish that.

Implement your joypad callback at the beginning of your main function:

JOY_init();
JOY_setEventHandler(&myJoyHandler);

And now you should be able to pause/resume the playback with a quick press of the Start button! Go ahead and try it out if you want.

Finally, let’s add a little pizazz. After setting the loop number and playing the music, draw some text on screen:

VDP_drawText("Welcome to Disco Zone!", 9,13);

Then define two variables directly below that. We’ll use them in a second:

u8 currentColor = 0;
u8 ticker = 0;

Now let’s get some colors going! Inside the game loop (that is, inside the while(1) loop) add this chunk of code:

if(paused == FALSE){
    ticker++;
    if (ticker == 60)
    {
        ticker = 0;
        if (currentColor < 5)
        {
            currentColor++;
        }
        else
        {
            currentColor = 0;
        }
        
        VDP_setPaletteColor(15, colors[currentColor]);
    }
}

Let’s step through it. First of all, this logic is only handled if the track is not paused; so the light show stops along with the music. Then we increase a ticker by 1 on each frame, and when one second has passed (because our amazing program runs at 60fps, naturally) we reset it to 0 to prevent overflows. And then the magic happens: currentColor will point to the color in our colors array that we currently want to display. We increase that value if there are still more colors in the array (we defined a total of 6 colors, so the maximum index is 5) or reset it to 0 if we’re already displaying the last color of the array.

Then we use VDP_setPaletteColor to grab the color we want from the array and apply it to the text. (If you’re not quite sure how that works, check out my tutorial on the topic of text color!) And if you want a really disorienting disco experience (and don’t suffer from epilepsy) replace the index 15 with 0.

Now compile the rom, run it and get funky! Or groovy, or rock out, or whatever you do to the music you picked.

images/disco.gif

If you have any questions, comments or criticism, post them in the comments below or reach out to me on Twitter @ohsat_games! Special thanks to Stephane Dallongeville for creating SGDK and everyone in the SGDK Discord for their help and keeping the dream alive!

Take It to the Next Level!

Want to boost your Mega Drive coding skills? Get exclusive bonus steps and project files for each tutorial by supporting me on Patreon!

Become a Patron!
Just Want to Buy Me a Coffee?

Check out the rest of this tutorial series!

  • Creating Graphics for the Mega Drive
  • Color Swapping
  • 4 Programs For Creating Mega Drive Graphics
  • Editing the Rom Header
  • Simple Game States
  • Creating a Simple Menu
  • Changing The Text Color in SGDK
  • Playing Music in SGDK
  • Converting VGZ to VGM
  • Get Words in Your Inbox!

    Be oldschool and sign up for my newsletter to get updates! Just enter your email address, prove you're not part of Skynet and you're good to go!



    Powered by CleverReach. I will not send you spam or sell/give your email address to someone else.  You can of course unsubscribe at any time. By clicking the subscribe button above, you confirm that you have read and agreed to our privacy policy.

    By using the Disqus service you confirm that you have read and agreed to the privacy policy.

    comments powered by Disqus

    Related Posts

    Streets of Rage 2 Design Docs

    A few years ago, Yuzo Koshiro posted a pile of old game design documents for Bare Knuckle 2 aka Streets of Rage 2 on the Ancient blog to commemorate the release of Streets of Rage 2 3D on the Nintendo 3DS. These documents gave a deep insight into the game’s inner workings, technical aspects, designs and even some cut content. They were an awesome resource for one of the most awesome games ever created.

    Read More

    Make a Space Shooter for the Mega Drive!

    It’s time for another SGDK tutorial series! After doing a single player Pong game and an endless runner, it’s time to reach for the stars… and make a space shooter! Apart from things like scrolling and animating sprites, this new series will show you how to deal with multiple entities and their collisions, how to randomly generate backgrounds and more! This project builds upon the previous tutorials, so if you’re new to SGDK programming and have not done those yet, I highly recommend starting with Megapong.
    Read More

    Patreon Revamps

    Hey there, what’s up? Things are continuing to evolve, as I’ve now updated my Patreon to give patrons more perks! Apart from early access to new tutorials and posts, the biggest one is probably the ability to peek behind the scenes…and there will be a lot to peek at in the coming months! This year I’m writing and submitting my MA thesis, meaning that I will have to do more stuff to make ends meet.
    Read More