Skip to content

Commit 8031c95

Browse files
authored
Merge pull request #116 from joebaird/main
Add call to stop audio playback
2 parents a160fd1 + 02a7b86 commit 8031c95

File tree

2 files changed

+22
-8
lines changed

2 files changed

+22
-8
lines changed

adafruit_pyportal/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ def __init__(
185185
self.set_backlight = self.peripherals.set_backlight
186186
self.sd_check = self.peripherals.sd_check
187187
self.play_file = self.peripherals.play_file
188+
self.stop_play = self.peripherals.stop_play
188189

189190
self.image_converter_url = self.network.image_converter_url
190191
self.wget = self.network.wget

adafruit_pyportal/peripherals.py

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ def __init__(self, spi, display, splash_group, debug=False):
6262
self.audio = audioio.AudioOut(board.SPEAKER)
6363
else:
6464
raise AttributeError("Board does not have a builtin speaker!")
65+
self.wavfile = None
6566

6667
if debug:
6768
print("Init SD Card")
@@ -144,16 +145,28 @@ def play_file(self, file_name, wait_to_finish=True):
144145
"""Play a wav file.
145146
146147
:param str file_name: The name of the wav file to play on the speaker.
148+
:param bool wait_to_finish: flag to determine if this is a blocking call
147149
148150
"""
149-
with open(file_name, "rb") as wavfile:
150-
wavedata = audiocore.WaveFile(wavfile)
151-
self._speaker_enable.value = True
152-
self.audio.play(wavedata)
153-
if not wait_to_finish:
154-
return
155-
while self.audio.playing:
156-
pass
151+
152+
# pylint: disable=consider-using-with
153+
# can't use `with` because we need wavefile to remain open after return
154+
self.wavfile = open(file_name, "rb")
155+
wavedata = audiocore.WaveFile(self.wavfile)
156+
self._speaker_enable.value = True
157+
self.audio.play(wavedata)
158+
if not wait_to_finish:
159+
return
160+
while self.audio.playing:
161+
pass
162+
self.wavfile.close()
163+
self._speaker_enable.value = False
164+
165+
def stop_play(self):
166+
"""Stops playing a wav file."""
167+
self.audio.stop()
168+
if self.wavfile is not None:
169+
self.wavfile.close()
157170
self._speaker_enable.value = False
158171

159172
def sd_check(self):

0 commit comments

Comments
 (0)