RETRO Music Engine

I was tinkering around with different options for generating sound and I thought I would share this. It executes Music Macro Language scripts and will play them on the speaker. Ideal for a music track in your RETRO game…

Here is a small sample of how to use it


 #include "mbed.h"
 #include "MusicEngine.h"

DigitalOut led1(P0_9);
DigitalOut led2(P0_8);

MusicEngine music(P0_18);

void musicCompleted()
{    
    led2 = 1;
}

main()
{
    music.setCompletionCallback(&musicCompleted);
    music.play("T224L8O5CL16>C<P16GP16L8EL16P16>C<GP16L8E.L16P16L8C#L16>C#<P16G#P16L8FL16P16>C#<G#P16L8F.L16P16L8CL16>C<P16GP16L8EL16P16>C<GP16L8E.L16P16D#EFP16FF#GP16GG#AP16L8>C<P8L4>C");
    
    while(1)
    {
        led1 = !led1;
        wait(0.25);
    }
}


Led1 will flash continuously even while the music plays and Led2 will switch on when the music sequence completed.

You can learn more about MML on Wikipedia

Have fun and let me know if you find any issues.

3 Likes

Interesting approach. I have implementated a multichannel sound engine as well. Cleaning it up before sharing.

1 Like

@ Architect - I would be interested in comparing notes. For my games I am submitting I have a 4 channel sound effecs engine, at most I am only using 2 channels. I fiddled with many different approaches, will be nice to see some other ideas.

@ taylorza -

SIR
Do you ever sleep?

Hi @ taylorza - I just tried it out and your example works great!

However, when trying it in my current project, I did notice noise coming from the speaker when not playing music. Still figuring out what causes that (and replacing some older code).

(BTW: to compare it with other code, I also tried the PwmSound library by Paul Griffith on the Retro, but the test program I couldn’t get to work on the Retro. Unfortunately I have no time to debug or try others)

To silence the speaker I am setting the PWM duty cycle and period to 0, but there still seems to be a hum on the speaker. I have not looked at the PWM implementation in any detail to understand the best way to eliminate the hum, but what might do the trick is to just change the pin function to GPIO and back to PWM when needed. I will give it a shot when I get home this evening. Thanks.

@ wilgeorge - I sleep far too little, I feel it every morning :slight_smile:

I compared the code to the pong sample. One way to succesfully stop the humming:

PwmOut pwm(P0_18);
pwm.write(0.00);

I guess the silencing is executed when reinitializing, as the write does the same as the assignment you have in your code. Unfortunately combining this with my code gave unwanted clicks. For now best silencing was obtained by adding this code to the constructor and to the executeCommand() method of the MusicEngine class:

_pwm.period_ms(1);
_pwm.write(0.0);
1 Like

@ maxint - Thanks for looking into this, I just implemented your suggestion and it looks (sounds?) like it is doing the trick.

Committed and published!