2.8. Sound - Bleeps and Bloops#
There are three libraries that you can use to make sound:
audiois a lower level library for generating arbitrary soundmusicis a higher level library for generating melodiesspeechis a library for converting text into speech
2.8.1. Speaker Control#
The built-in speaker can be controlled by using the following functions to turn it off or on:
speaker_off()speaker_on()
2.8.2. Playing Sounds#
Use audio.play to play a sound
audio.play(source, wait=True)
where
sourceis a either aSound(built-in) orSoundEffect(custom)waitdetermines whether the function will block execution of code until the sound is finished
2.8.3. Built in Sounds#
There are a number of built in sounds such as:
Sound.HELLOSound.HAPPYSound.SAD
that can be played using audio.play e.g.
from microbit import *
while True:
if button_a.is_pressed():
audio.play(Sound.HAPPY)
elif button_b.is_pressed():
audio.play(Sound.SAD)
2.8.4. Sound Effects#
A SoundEffect is a configurable sound that we can play with audio.play.
The constructor for a SoundEffect is:
audio.SoundEffect(freq_start=500, freq_end=2500, duration=500, vol_start=255, vol_end=0, waveform=WAVEFORM_SQUARE, fx=FX_NONE, shape=SHAPE_LOG)
where:
freq_startis the start frequency in Hertz (Hz)freq_endis the end frequency in Hertz (Hz)durationspecifies how long the sound effect lasts (ms)vol_startandvol_endspecify the volume at start and end in the range 0 to 255.waveformspecifies the type of waveform to use e.g.WAVEFORM_SINEorWAVEFORM_SAWTOOTHfxis an effect applied to the soundshapeis the interpolation method between start and end frequencies
More details at https://microbit-micropython.readthedocs.io/en/v2-docs/audio.html#audio.SoundEffect
Example#
from microbit import *
sound = audio.SoundEffect(
freq_start=400,
freq_end=2000,
duration=500,
vol_start=100,
vol_end=255,
waveform=audio.SoundEffect.WAVEFORM_TRIANGLE,
fx=audio.SoundEffect.FX_VIBRATO,
shape=audio.SoundEffect.SHAPE_LOG,
)
audio.play(sound)