9. Audio


9.1. Library

This module allows you play sounds with the microbit.
Put import audio at the top under from microbit import *.
By default, sound output will be via the edge connector on pin 0 and the built-in speaker in V2.
from microbit import *
import audio

9.2. main controls

audio.play(source, wait=True, pin=pin0)
Play the source of the sound.
source can be a built-in sound or an iterable of AudioFrame elements.
If wait is True, this function will block until the source has been completely played.
pin is on optional argument to specify the output pin with default of pin0. Use pin=None to make no sound.
audio.is_playing()
Returns True if audio is playing, otherwise returns False.
audio.stop()

Stops all audio playback.


9.3. V2 Built-in sounds

The built-in sounds can be called using audio.play(Sound.NAME).

  • Sound.GIGGLE

  • Sound.HAPPY

  • Sound.HELLO

  • Sound.MYSTERIOUS

  • Sound.SAD

  • Sound.SLIDE

  • Sound.SOARING

  • Sound.SPRING

  • Sound.TWINKLE

  • Sound.YAWN

from microbit import *
import audio

audio.play(Sound.GIGGLE)
The code below uses a for-loop to loop through each Sound in the sound_list and play it.
from microbit import *
import audio

sound_list = [Sound.GIGGLE, Sound.TWINKLE]
for sound in sound_list:
    audio.play(sound)

9.4. All Built in sounds

The code below plays all the built-in sounds.
The A-button can be pressed to exit the for-loop then the while-loop using break.
Pressing the reset button on the back of the microbit will restart the code.
from microbit import *
import audio

built_in_sounds = [
    Sound.GIGGLE,
    Sound.HAPPY,
    Sound.HELLO,
    Sound.MYSTERIOUS,
    Sound.SAD,
    Sound.SLIDE,
    Sound.SOARING,
    Sound.TWINKLE,
    Sound.YAWN,
]
while True:
    for sound in built_in_sounds:
        audio.play(sound)
        sleep(1000)
        if button_a.is_pressed():
            break
    if button_a.is_pressed():
        break

Tasks

  1. Play any 3 built-in sounds using a list, separating them with a 1 second pause.

  2. Use the choice function to randomly pick a built-in sound from a sound list. See: https://www.w3schools.com/python/ref_random_choice.asp. Use button pressing to break out of the while-loop to stop playing sounds.

Play any 3 built-in sounds using a list, separating them with a 1 second pause.

from microbit import *
import audio

sound_list = [Sound.SAD, Sound.HAPPY, Sound.YAWN,]
for sound in sound_list:
    audio.play(sound)
    sleep(1000)

Use the choice function to randomly pick a built-in sound from a sound list. See: https://www.w3schools.com/python/ref_random_choice.asp. Use button pressing to break out of the while-loop to stop playing sounds.

from microbit import *
import audio
from random import choice as rand_choice

sound_list = [Sound.SAD, Sound.HAPPY, Sound.YAWN]

while True:
    audio.play(rand_choice(sound_list))
    sleep(1000)
    if button_a.is_pressed():
        break