9. Audio
9.1. Library
import audio
at the top under from microbit import *
.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 isTrue
, this function will block until the source has been completely played.pin is on optional argument to specify the output pin with default ofpin0
. Usepin=None
to make no sound.
- audio.is_playing()
- Returns
True
if audio is playing, otherwise returnsFalse
.
- 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)
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
break
.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
Play any 3 built-in sounds using a list, separating them with a 1 second pause.
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