In this lesson, you'll create a sound sampler and playback device using your Micro:bit's microphone and speaker. You'll start by detecting sound events, then progress to sampling sound levels to 'record' your voice as a sequence of levels, and finally 'playback' those levels as a melody of tones. This project reinforces control structures, lists for data storage, and using hardware modules. Note: The Micro:bit can't record actual audio, but we'll simulate recording by sampling sound intensity levels and playing them back as pitches.
By the end, your Micro:bit will record a short voice sample as sound levels and play it back as tones. Open the Micro:bit Python editor at python.microbit.org and start a new project.
Start by importing the necessary modules. We'll need the microbit module to access the hardware, including the microphone, display, and buttons. We'll also import the music module for playback later.
Add the following complete code to your editor:
from microbit import *
import music
Let's detect simple sound events using microphone.current_event(). This returns 'loud' if the sound is above a threshold or 'quiet' otherwise. We'll check in a loop and show a happy face if loud (e.g., when you speak).
Update your code to this complete version:
from microbit import *
import music
while True:
event = microphone.current_event()
if event == SoundEvent.LOUD:
display.show(Image.HAPPY)
else:
display.clear()
sleep(100)
Now, let's sample the actual sound level using microphone.sound_level(), which returns a value from 0 (quiet) to 255 (loud). Think of sound level as a measure of how intense or loud the sound is at any given moment – it's like taking a snapshot of the sound's volume. The units are arbitrary numbers from 0 to 255, where 0 means complete silence (no sound detected), and 255 represents the loudest sound the Micro:bit's microphone can pick up. This isn't recording the actual audio waveform (like a voice recorder would), but rather sampling the loudness repeatedly to capture a pattern of how the volume changes over time. We'll display it scrolled on the screen in a loop.
Update your code to this complete version:
from microbit import *
import music
while True:
level = microphone.sound_level()
display.scroll(str(level))
sleep(500)
Next, we'll record a short sample when button A is pressed. We'll store 20 sound levels in a list over 2 seconds (sampling every 100ms). This captures a pattern of your voice. After recording, scroll 'Recorded'.
Update your code to this complete version:
from microbit import *
import music
samples = [] # List to store sound levels
while True:
if button_a.is_pressed():
samples = [] # Clear previous samples
display.show(Image.YES)
for i in range(20): # Record 20 samples
level = microphone.sound_level()
samples.append(level)
sleep(100)
display.scroll("Recorded")
sleep(100)