2

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?

Greenonline
3,1527 gold badges36 silver badges48 bronze badges
asked Jan 19, 2017 at 11:44
3
  • Interleave the music and game code. Do not delay when playing music or in the game code. Alternatively use threads. Commented Jan 19, 2017 at 12:06
  • 1
    Use a couple of Finite State Machines to play both the music an the game together. Commented Jan 19, 2017 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) Commented Jan 19, 2017 at 13:47

2 Answers 2

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.

answered Jan 19, 2017 at 15:27
1

Run the music through a time Interrupt.

answered Jan 19, 2017 at 14:02

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.