Skip to content

Music Jukebox

Level Beginner
Board V1 & V2
Parts micro:bit · V1 only: buzzer or headphones on pin 0 and GND
Source 14 music.py

What you'll build

A pocket jukebox:

Input Plays
Button A Beethoven's Ode to Joy (built in)
Button B Frère Jacques, written as a list of notes
Shake A siren that sweeps up and down

Wiring

micro:bit V2 plays through its built-in speaker, so you don't need to wire anything.

micro:bit V1 has no speaker. Connect a buzzer or headphones between P0 and GND:

Part Part pin micro:bit pin
Buzzer or headphones + P0
Buzzer or headphones − GND
Buzzer or headphones+−micro:bitP0GND

Code

14 music.py
'''
Example: Mini jukebox with the music module in micro:bit
By: Meqdad Darwish
'''
# Note: micro:bit V2 plays through its built-in speaker.
# On V1, connect a buzzer or headphones to pin0 and GND.

from microbit import *
import music

# "Frere Jacques": note + octave, then ":" and length in ticks
FRERE_JACQUES = ["C4:4", "D4:4", "E4:4", "C4:4",
                 "C4:4", "D4:4", "E4:4", "C4:4",
                 "E4:4", "F4:4", "G4:8",
                 "E4:4", "F4:4", "G4:8"]

while True:
    if button_a.was_pressed():
        display.show(Image.MUSIC_QUAVER)
        music.play(music.ODE)  # a built-in melody
        display.clear()
    elif button_b.was_pressed():
        display.show(Image.MUSIC_CROTCHET)
        music.play(FRERE_JACQUES)
        display.clear()
    elif accelerometer.was_gesture("shake"):
        display.show(Image.SURPRISED)
        for frequency in range(880, 1760, 16):  # siren up...
            music.pitch(frequency, 6)
        for frequency in range(1760, 880, -16):  # ...and down
            music.pitch(frequency, 6)
        display.clear()
    sleep(20)

How it works

  • music.play() plays a list of notes, or one of the built-in tunes like music.ODE, music.NYAN or music.BIRTHDAY.
  • Each note is written "C4:4": the note (C), the octave (4) and the length in ticks (4). At the default tempo a tick is 125 ms, so :4 lasts half a second and :8 a whole second.
  • music.pitch(frequency, duration) plays any frequency in Hz. The siren loops from 880 Hz to 1760 Hz and back in 6 ms steps.

Try this next

  • Write your own tune, or slow it down with music.set_tempo(bpm=80).
  • Play a different note for each tilt direction, like a theremin, using accelerometer.get_x().
  • Build a Fruit Piano to play notes by touch.