2.9. Sound - Music#
2.9.1. Playing Music#
Use music.play to play a melody
music.play(music, wait=True, loop=False)
where
musicis a list of notes (see “Custom Melodies” below)waitdetermines whether the function will block execution of code until the music is finishedloopdetermines whether to repeat the playback
2.9.2. Tempo#
You can set the tempo of music playback by using
music.set_tempo(ticks=4, bpm=120)
where:
ticks is the number of sub-divisions per beat, to give finer control over duration of notes
bpm is the number of beats per minute
2.9.3. Stopping and Resetting#
You can stop the music with
music.stop()
or reset the music playback to default settings with:
music.reset()
2.9.4. Built in Music#
The music library contains example melodies that can be played for example:
music.NYANmusic.DADADADUMmusic.BIRTHDAY
You can find the full list here https://microbit-micropython.readthedocs.io/en/v2-docs/music.html#built-in-melodies
Example#
from microbit import *
import music
music.play(music.NYAN)
2.9.5. Custom Melodies#
A custom melody can be created with a list of notes, which are defined using strings of the form:
NOTE[octave][:duration]
for example
C4:2
refers to middle “C”. It is the C in the 4th octave, played for a duration of 2 ticks.
The opening of Beethoven’s 5th Symphony would be written as:
['r4:2', 'g', 'g', 'g', 'eb:8', 'r:2', 'f', 'f', 'f', 'd:8']
Example#
from microbit import *
import music
melody = ["r4:2", "g", "g", "g", "eb:8", "r:2", "f", "f", "f", "d:8"]
music.play(melody)