2.8. Sound - Bleeps and Bloops#

There are three libraries that you can use to make sound:

  • audio is a lower level library for generating arbitrary sound

  • music is a higher level library for generating melodies

  • speech is 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

  • source is a either a Sound (built-in) or SoundEffect (custom)

  • wait determines 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.HELLO

  • Sound.HAPPY

  • Sound.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_start is the start frequency in Hertz (Hz)

  • freq_end is the end frequency in Hertz (Hz)

  • duration specifies how long the sound effect lasts (ms)

  • vol_start and vol_end specify the volume at start and end in the range 0 to 255.

  • waveform specifies the type of waveform to use e.g. WAVEFORM_SINE or WAVEFORM_SAWTOOTH

  • fx is an effect applied to the sound

  • shape is 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)