Playing audio files on the micro:bit
Posted: Mon Mar 27, 2017 7:40 pm
I have been experimenting with the audio module. The example provided in the documentation opens the possibility to play audio files. I have not been able to store files larger than 4KB so the only solution I have found is to split larger files into 4KB chunks. This can be easily done in Audacity with Analyze-Regular interval labels and then File-Export Multiple. Although the values accepted by the audio.play function are supposed to be signed bytes between -128 and 127 I have been successful exporting the files in raw format, header-less, with unsigned 8 bits PCM. They sound quite OK on the micro:bit.
Assuming around 30KB of storage, at a 8KHz sampling frequency it gives around 3.5 seconds of recording sound.
Here is a sample code to play the attached files. They are based on the sound at https://www.freesound.org/people/urupin/sounds/199905/ , which has a CC0 license.
Anyone can think of a way of storing more than 3.5 seconds (without using an external sd card)? I was thinking on some kind of basic ADPCM, but it seems that the 2ms that the interrupt has to process the sound is not enough to do even a simple loop through the 32 elements of the AudioFrame...
Assuming around 30KB of storage, at a 8KHz sampling frequency it gives around 3.5 seconds of recording sound.
Here is a sample code to play the attached files. They are based on the sound at https://www.freesound.org/people/urupin/sounds/199905/ , which has a CC0 license.
Code: Select all
import audio
def read_frame(f_list, frame):
for file in f_list:
ln = file.readinto(frame)
while ln:
yield frame
ln = file.readinto(frame)
def play_file(f):
with open(f + "-01.raw", "rb") as file1, \
open(f + "-02.raw", "rb") as file2, \
open(f + "-03.raw", "rb") as file3, \
open(f + "-04.raw", "rb") as file4:
f_list = [file1, file2, file3, file4]
audio.play(read_frame(f_list, frame), wait=True)
# Allocate memory outside the interrupt
frame = audio.AudioFrame()
ln = -1
file = 1
# play the files
play_file("robot")