Switching instruments on the fly while a song is playing

Topics related to the API, programming discussions & questions, coding tips, bugs, etc. should go here.
Post Reply
User avatar
Artcfox
Posts: 1382
Joined: Thu Jun 04, 2015 5:35 pm
Contact:

Switching instruments on the fly while a song is playing

Post by Artcfox »

I've been experimenting with different instruments for the MIDI songs in my Uzebox game, and I wanted to do a quick A/B comparison between different patches for the instruments without having to recompile anything. This is what I came up with.

Define two (or more) patches structures in PROGMEM that have different instruments in the beginning depending on how many tracks your MIDI uses, but keep the same sound effects after (unless you want those to change too):

Code: Select all

const struct PatchStruct patches[] PROGMEM = {
// Instruments
{0,NULL,square_piano,0,0},
{0,NULL,flute,0,0},

// Sound Effects
{0,NULL,jump,0,0},
{1,NULL,clop,0,0},
{0,NULL,fart,0,0},
{0,NULL,treasure,0,0},
{0,NULL,death,0,0},
};

const struct PatchStruct patches2[] PROGMEM = {
// Instruments
{0,NULL,patch04,0,0},
{0,NULL,flute_bass,0,0},

// Sound Effects
{0,NULL,jump,0,0},
{1,NULL,clop,0,0},
{0,NULL,fart,0,0},
{0,NULL,treasure,0,0},
{0,NULL,death,0,0},
};
And then in your main code, when you want to toggle between them, you can do something like this:

Code: Select all

    if (p.buttons.pressed & BTN_SL) {
      extern const Patch *patchPointers;
      if (patchPointers == patches)
        patchPointers = patches2;
      else
        patchPointers = patches;
    }
and then the music will instantly switch to the different instruments, while the sound effects remain unchanged.

One idea I had for this was to make different variations of the instruments, that either sound muffled, or quieter in some way, and then change the patch structure on the fly depending on what happens. Maybe if your character goes underwater, the music can sound muffled, or the volume can be proportional to the distance you are from some object in the game. Or maybe a "music type" slider in a menu that lets the user select which instruments to use.
User avatar
danboid
Posts: 1935
Joined: Sun Jun 14, 2020 12:14 am

Re: Switching instruments on the fly while a song is playing

Post by danboid »

This sounds very useful and so it's surprising its not been done already considering how little code is involved.

Thanks for sharing it Artcfox!
User avatar
uze6666
Site Admin
Posts: 4801
Joined: Tue Aug 12, 2008 9:13 pm
Location: Montreal, Canada
Contact:

Re: Switching instruments on the fly while a song is playing

Post by uze6666 »

One idea I had for this was to make different variations of the instruments, that either sound muffled, or quieter in some way, and then change the patch structure on the fly depending on what happens.
Though patches must be the same length in each set, this is a very interesting idea, never thought hot swapping patch sets.
Post Reply