Skip to content

Commit 76c7f7a

Browse files
committed
add play_mp3 function to bluefruit module
1 parent d466ca9 commit 76c7f7a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

adafruit_circuitplayground/bluefruit.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
import digitalio
4343
import board
4444
import audiopwmio
45+
import audiomp3
4546
import audiobusio
4647
from adafruit_circuitplayground.circuit_playground_base import CircuitPlaygroundBase
4748

@@ -151,6 +152,41 @@ def loud_sound(self, sound_threshold=200):
151152

152153
return self.sound_level > sound_threshold
153154

155+
def play_mp3(self, file_name):
156+
""" Play a .mp3 file using the onboard speaker.
157+
158+
:param file_name: The name of your .mp3 file in quotation marks including .mp3
159+
160+
.. image :: ../docs/_static/speaker.jpg
161+
:alt: Onboard speaker
162+
163+
To use with the Circuit Playground Bluefruit:
164+
165+
.. code-block:: python
166+
167+
from adafruit_circuitplayground import cp
168+
169+
while True:
170+
if cp.button_a:
171+
cp.play_mp3("laugh.mp3")
172+
elif cp.button_b:
173+
cp.play_mp3("rimshot.mp3")
174+
"""
175+
if file_name.lower().endswith(".mp3"):
176+
# Play a specified file.
177+
self.stop_tone()
178+
self._speaker_enable.value = True
179+
with self._audio_out(
180+
board.SPEAKER
181+
) as audio: # pylint: disable=not-callable
182+
mp3file = audiomp3.MP3Decoder(open(file_name, "rb"))
183+
audio.play(mp3file)
184+
while audio.playing:
185+
pass
186+
self._speaker_enable.value = False
187+
else:
188+
raise ValueError("Filetype must be mp3")
189+
154190

155191
cpb = Bluefruit() # pylint: disable=invalid-name
156192
"""Object that is automatically created on import.

0 commit comments

Comments
 (0)