How to do it...

Let's perform the following steps:

  1. Run the following lines of code in the REPL. You should hear the E5 musical note play on the speakers for 0.15 seconds:
>>> import time
>>> from adafruit_circuitplayground.express import cpx
>>> 
>>> E5 = 659
>>> C5 = 523
>>> G5 = 784
>>> 
>>> def play_note(note, duration=0.15):
...     if note == 0:
...         time.sleep(duration)
...     else:
...         cpx.play_tone(note, duration)
... 
>>> play_note(E5)
  1. Use the following lines of code to play the same note at twice the speed, and then at half the speed:
>>> play_note(E5, 0.15 / 2)
>>> play_note(E5, 0.15 * 2)
  1. Use the following line of code to play nothing and keep the speaker silent for the same period as one note playing at the normal speed:
>>> play_note(0)
  1. Use the following lines of code to play the initial part of the Super Mario Bros. theme song:
>>> MELODY = (E5, E5, 0, E5, 0, C5, E5, 0, G5)
>>> for note in MELODY:
...     play_note(note)
... 
>>> 
  1. The code that follows combines all the code shown in this recipe to make one complete program. Add this to the main.py file and it will play the start of the Super Mario Bros. theme song every time you reload the code:
import time
from adafruit_circuitplayground.express import cpx

E5 = 659
C5 = 523
G5 = 784

MELODY = (E5, E5, 0, E5, 0, C5, E5, 0, G5)

def play_note(note, duration=0.15):
    if note == 0:
        time.sleep(duration)
    else:
        cpx.play_tone(note, duration)

for note in MELODY:
    play_note(note)