1

I have some background music. If I put it at the top of the void loop(), it'll first play the music and then execute the game code afterwards.

How do I have the code run while the background music is playing?

3
  • Interleave the music and game code. Do not delay when playing music or in the game code. Alternatively use threads. Jan 19 '17 at 12:06
  • 1
    Use a couple of Finite State Machines to play both the music an the game together.
    – Majenko
    Jan 19 '17 at 13:03
  • 2
    I would set time to minimal note lenght and set PWM to play next tone/pause from music array inside the iterrupt. It would be so fast, that the game probabelly would not notice, it is interrupted on the background each beat time (few per sec) for just couple of cycles (1/16.000.000 sec each)
    – gilhad
    Jan 19 '17 at 13:47
2

It all depends on the architecture of your game. The first games probably interleaved their music and gameplay, as the comment above says. This is probably the level of complexity you are looking for, on an Arduino.

First you need to pick some "framerate" that the game advances with. You could, for example, play 4 frames of music for every video frame, or something like that. It also depends how you are playing music. If you are just playing notes with the analog out, this approach would work. Here is some pseudocode that updates the PWM output 4 times faster than the game code:

set n = 0
set quit = false

// main game loop
while !quit
    // set music output pwm here
    if n % 4 == 0
        // advance game here
    endif
    n++
endwhile

If you are playing music from something like an SD card, you are constrained by the bit rate of the music.

Also, here is an article on Arduino protothreading that might interest you. https://create.arduino.cc/projecthub/reanimationxp/how-to-multithread-an-arduino-protothreading-tutorial-dd2c37. My suggestion is to look at how the old game systems implemented their state machines.

1

Run the music through a time Interrupt.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.