Compressed audio can be a nice alternative to uncompressed WAV files - especially when you have a small filesystem like that on many CircuitPython boards: those WAV files get pretty big fast! Thanks to the expiration of the MP3 patent pool, we can now include MP3 decoding as a core CircuitPython capability.
CircuitPython supports any MP3 file you like. We've found that mono and stereo files from 32kbit/s to 128kbit/s work, with sample rates from 16kHz to 44.1kHz. The DAC output on the SAMD51 M4 is just 12-bit so there's not much point in using higher bitrates.
With this example, tailored to the PyGamer, you can loop MP3s to your heart's content (or as long as power lasts). Put the MP3 files in the main folder of your SD card, put the code below in code.py, and make sure you've configured mount_sd.py!
This example can be adapted to a lot of SAMD51 and nRF52840 boards. Where there's no headphone jack or speaker connection, consider the Prop Maker Featherwing for your sound-making needs. For more about playing MP3s, visit the page in the essentials guide. For a full MP3 player for your PyGamer, see the dedicated guide.
# SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries # # SPDX-License-Identifier: MIT import os import time import board import digitalio # Updating the display can interfere with MP3 playback if it is not # done carefully try: board.DISPLAY.auto_refresh = False except: # pylint: disable=bare-except pass from audiomp3 import MP3Decoder # pylint: disable=wrong-import-position try: from audioio import AudioOut except ImportError: try: from audiopwmio import PWMAudioOut as AudioOut except ImportError: pass # not always supported by every board! # The mp3 files on the sd card will be played in alphabetical order mp3files = sorted("/sd/" + filename for filename in os.listdir("/sd") if filename.lower().endswith("mp3")) voodoo = [1,2,3] # You have to specify some mp3 file when creating the decoder mp3 = open(mp3files[0], "rb") decoder = MP3Decoder(mp3) audio = AudioOut(board.A0, right_channel=board.A1) speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE) speaker_enable.switch_to_output(True) while True: for filename in mp3files: print("Playing", filename) # Updating the .file property of the existing decoder # helps avoid running out of memory (MemoryError exception) decoder.file = open(filename, "rb") audio.play(decoder) # This allows you to do other things while the audio plays! while audio.playing: time.sleep(1)


