Speaker
The StudioBot is equiped with a basic speaker. This is suitable for playing simple sounds and complex sounds that come from an MP3 source.
Basic Sounds
The most basic sounds can be a simple tone.
import board
import simpleio
simpleio.tone(board.DAC, 440, duration=1.0)
We can make tones from the speaker
from audiocore import RawSample
from audioio import AudioOut
import board
import time
import audiobusio
import array
import math
tone_volume = 0.1 # Increase this to increase the volume of the tone.
frequency = 440 # Set this to the Hz of the tone you want to generate.
length = 8000 // frequency
sine_wave = array.array("H", [0] * length)
for i in range(length):
sine_wave[i] = int((1 + math.sin(math.pi * 2 * i / length)) * tone_volume * (2 ** 15 - 1))
audio = AudioOut(board.DAC)
sine_wave_sample = RawSample(sine_wave)
audio.play(sine_wave_sample, loop=True)
time.sleep(1) #how long we want to play the sound for
audio.stop()
MP3 Files
Our Robot can actually play MP3 files
import board
import digitalio
from audiomp3 import MP3Decoder
try:
from audioio import AudioOut
except ImportError:
try:
from audiopwmio import PWMAudioOut as AudioOut
except ImportError:
pass # not always supported by every board!
button = digitalio.DigitalInOut(board.SWITCH1)
button.switch_to_input(pull=digitalio.Pull.UP)
# The listed mp3files will be played in order
mp3files = ["begins.mp3"]
# You have to specify some mp3 file when creating the decoder
mp3 = open(mp3files[0], "rb")
decoder = MP3Decoder(mp3)
audio = AudioOut(board.DAC)
while True:
for filename in mp3files:
# Updating the .file property of the existing decoder
# helps avoid running out of memory (MemoryError exception)
decoder.file = open(filename, "rb")
audio.play(decoder)
print("playing", filename)
# This allows you to do other things while the audio plays!
while audio.playing:
pass
print("Waiting for button press to continue!")
while button.value:
pass
Further examples and information can be found in this Adafruit article.
Last updated