Skip to content

Commit e34b242

Browse files
committed
i2s audio examples
1 parent 6eb0f90 commit e34b242

30 files changed

+1347
-0
lines changed
65.6 KB
Binary file not shown.
57.8 KB
Binary file not shown.
6.51 KB
Binary file not shown.
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
# SPDX-FileCopyrightText: 2023 Christopher Parrott for Pimoroni Ltd
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import os
6+
import math
7+
import struct
8+
from machine import I2S
9+
10+
"""
11+
A class for playing Wav files out of an I2S audio amp. It can also play pure tones.
12+
This code is based heavily on the work of Mike Teachman, at:
13+
https://github.com/miketeachman/micropython-i2s-examples/blob/master/examples/wavplayer.py
14+
"""
15+
16+
17+
class WavPlayer:
18+
# Internal states
19+
PLAY = 0
20+
PAUSE = 1
21+
FLUSH = 2
22+
STOP = 3
23+
NONE = 4
24+
25+
MODE_WAV = 0
26+
MODE_TONE = 1
27+
28+
# Default buffer length
29+
SILENCE_BUFFER_LENGTH = 1000
30+
WAV_BUFFER_LENGTH = 10000
31+
INTERNAL_BUFFER_LENGTH = 20000
32+
33+
TONE_SAMPLE_RATE = 44_100
34+
TONE_BITS_PER_SAMPLE = 16
35+
TONE_FULL_WAVES = 2
36+
37+
def __init__(self, id, sck_pin, ws_pin, sd_pin, ibuf_len=INTERNAL_BUFFER_LENGTH, root="/"):
38+
self.__id = id
39+
self.__sck_pin = sck_pin
40+
self.__ws_pin = ws_pin
41+
self.__sd_pin = sd_pin
42+
self.__ibuf_len = ibuf_len
43+
44+
# Set the directory to search for files in
45+
self.set_root(root)
46+
47+
self.__state = WavPlayer.NONE
48+
self.__mode = WavPlayer.MODE_WAV
49+
self.__wav_file = None
50+
self.__loop_wav = False
51+
self.__first_sample_offset = None
52+
self.__flush_count = 0
53+
self.__audio_out = None
54+
55+
# Allocate a small array of blank audio samples used for silence
56+
self.__silence_samples = bytearray(self.SILENCE_BUFFER_LENGTH)
57+
58+
# Allocate a larger array for WAV audio samples, using a memoryview for more efficient access
59+
self.__wav_samples_mv = memoryview(bytearray(self.WAV_BUFFER_LENGTH))
60+
61+
# Reserve a variable for audio samples used for tones
62+
self.__tone_samples = None
63+
self.__queued_samples = None
64+
65+
def set_root(self, root):
66+
self.__root = root.rstrip("/") + "/"
67+
68+
def play_wav(self, wav_file, loop=False):
69+
if os.listdir(self.__root).count(wav_file) == 0:
70+
raise ValueError(f"'{wav_file}' not found")
71+
72+
self.__stop_i2s() # Stop any active playback and terminate the I2S instance
73+
74+
self.__wav_file = open(self.__root + wav_file, "rb") # Open the chosen WAV file in read-only, binary mode
75+
self.__loop_wav = loop # Record if the user wants the file to loop
76+
77+
# Parse the WAV file, returning the necessary parameters to initialise I2S communication
78+
format, sample_rate, bits_per_sample, self.__first_sample_offset = WavPlayer.__parse_wav(self.__wav_file)
79+
80+
self.__wav_file.seek(self.__first_sample_offset) # Advance to first byte of sample data
81+
82+
self.__start_i2s(bits=bits_per_sample,
83+
format=format,
84+
rate=sample_rate,
85+
state=WavPlayer.PLAY,
86+
mode=WavPlayer.MODE_WAV)
87+
88+
def play_tone(self, frequency, amplitude):
89+
if frequency < 20.0 or frequency > 20_000:
90+
raise ValueError("frequency out of range. Expected between 20Hz and 20KHz")
91+
92+
if amplitude < 0.0 or amplitude > 1.0:
93+
raise ValueError("amplitude out of range. Expected 0.0 to 1.0")
94+
95+
# Create a buffer containing the pure tone samples
96+
samples_per_cycle = self.TONE_SAMPLE_RATE // frequency
97+
sample_size_in_bytes = self.TONE_BITS_PER_SAMPLE // 8
98+
samples = bytearray(self.TONE_FULL_WAVES * samples_per_cycle * sample_size_in_bytes)
99+
range = pow(2, self.TONE_BITS_PER_SAMPLE) // 2
100+
101+
format = "<h" if self.TONE_BITS_PER_SAMPLE == 16 else "<l"
102+
103+
# Populate the buffer with multiple cycles to avoid it completing too quickly and causing drop outs
104+
for i in range(samples_per_cycle * self.TONE_FULL_WAVES):
105+
sample = int((range - 1) * (math.sin(2 * math.pi * i / samples_per_cycle)) * amplitude)
106+
struct.pack_into(format, samples, i * sample_size_in_bytes, sample)
107+
108+
# Are we not already playing tones?
109+
if not (self.__mode == WavPlayer.MODE_TONE and (self.__state == WavPlayer.PLAY or self.__state == WavPlayer.PAUSE)):
110+
self.__stop_i2s() # Stop any active playback and terminate the I2S instance
111+
self.__tone_samples = samples
112+
self.__start_i2s(bits=self.TONE_BITS_PER_SAMPLE,
113+
format=I2S.MONO,
114+
rate=self.TONE_SAMPLE_RATE,
115+
state=WavPlayer.PLAY,
116+
mode=WavPlayer.MODE_TONE)
117+
else:
118+
self.__queued_samples = samples
119+
self.__state = WavPlayer.PLAY
120+
121+
def pause(self):
122+
if self.__state == WavPlayer.PLAY:
123+
self.__state = WavPlayer.PAUSE # Enter the pause state on the next callback
124+
125+
def resume(self):
126+
if self.__state == WavPlayer.PAUSE:
127+
self.__state = WavPlayer.PLAY # Enter the play state on the next callback
128+
129+
def stop(self):
130+
if self.__state == WavPlayer.PLAY or self.__state == WavPlayer.PAUSE:
131+
if self.__mode == WavPlayer.MODE_WAV:
132+
# Enter the flush state on the next callback and close the file
133+
# It is done in this order to prevent the callback entering the play
134+
# state after we close the file but before we change the state)
135+
self.__state = WavPlayer.FLUSH
136+
self.__wav_file.close()
137+
else:
138+
self.__state = WavPlayer.STOP
139+
140+
def is_playing(self):
141+
return self.__state != WavPlayer.NONE and self.__state != WavPlayer.STOP
142+
143+
def is_paused(self):
144+
return self.__state == WavPlayer.PAUSE
145+
146+
def __start_i2s(self, bits=16, format=I2S.MONO, rate=44_100, state=STOP, mode=MODE_WAV):
147+
import gc
148+
gc.collect()
149+
self.__audio_out = I2S(
150+
self.__id,
151+
sck=self.__sck_pin,
152+
ws=self.__ws_pin,
153+
sd=self.__sd_pin,
154+
mode=I2S.TX,
155+
bits=bits,
156+
format=format,
157+
rate=rate,
158+
ibuf=self.__ibuf_len,
159+
)
160+
161+
self.__state = state
162+
self.__mode = mode
163+
self.__flush_count = self.__ibuf_len // self.SILENCE_BUFFER_LENGTH + 1
164+
self.__audio_out.irq(self.__i2s_callback)
165+
self.__audio_out.write(self.__silence_samples)
166+
167+
def __stop_i2s(self):
168+
self.stop() # Stop any active playback
169+
while self.is_playing(): # and wait for it to complete
170+
pass
171+
172+
if self.__audio_out is not None:
173+
self.__audio_out.deinit() # Deinit any active I2S comms
174+
175+
self.__state == WavPlayer.NONE # Return to the none state
176+
177+
def __i2s_callback(self, arg):
178+
# PLAY
179+
if self.__state == WavPlayer.PLAY:
180+
if self.__mode == WavPlayer.MODE_WAV:
181+
num_read = self.__wav_file.readinto(self.__wav_samples_mv) # Read the next section of the WAV file
182+
183+
# Have we reached the end of the file?
184+
if num_read == 0:
185+
# Do we want to loop the WAV playback?
186+
if self.__loop_wav:
187+
_ = self.__wav_file.seek(self.__first_sample_offset) # Play again, so advance to first byte of sample data
188+
else:
189+
self.__wav_file.close() # Stop playing, so close the file
190+
self.__state = WavPlayer.FLUSH # and enter the flush state on the next callback
191+
192+
self.__audio_out.write(self.__silence_samples) # In both cases play silence to end this callback
193+
else:
194+
self.__audio_out.write(self.__wav_samples_mv[: num_read]) # We are within the file, so write out the next audio samples
195+
else:
196+
if self.__queued_samples is not None:
197+
self.__tone_samples = self.__queued_samples
198+
self.__queued_samples = None
199+
self.__audio_out.write(self.__tone_samples)
200+
201+
# PAUSE or STOP
202+
elif self.__state == WavPlayer.PAUSE or self.__state == WavPlayer.STOP:
203+
self.__audio_out.write(self.__silence_samples) # Play silence
204+
205+
# FLUSH
206+
elif self.__state == WavPlayer.FLUSH:
207+
# Flush is used to allow the residual audio samples in the internal buffer to be written
208+
# to the I2S peripheral. This step avoids part of the sound file from being cut off
209+
if self.__flush_count > 0:
210+
self.__flush_count -= 1
211+
else:
212+
self.__state = WavPlayer.STOP # Enter the stop state on the next callback
213+
self.__audio_out.write(self.__silence_samples) # Play silence
214+
215+
# NONE
216+
elif self.__state == WavPlayer.NONE:
217+
pass
218+
219+
@staticmethod
220+
def __parse_wav(wav_file):
221+
chunk_ID = wav_file.read(4)
222+
if chunk_ID != b"RIFF":
223+
raise ValueError("WAV chunk ID invalid")
224+
_ = wav_file.read(4) # chunk_size
225+
format = wav_file.read(4)
226+
if format != b"WAVE":
227+
raise ValueError("WAV format invalid")
228+
sub_chunk1_ID = wav_file.read(4)
229+
if sub_chunk1_ID != b"fmt ":
230+
raise ValueError("WAV sub chunk 1 ID invalid")
231+
_ = wav_file.read(4) # sub_chunk1_size
232+
_ = struct.unpack("<H", wav_file.read(2))[0] # audio_format
233+
num_channels = struct.unpack("<H", wav_file.read(2))[0]
234+
235+
if num_channels == 1:
236+
format = I2S.MONO
237+
else:
238+
format = I2S.STEREO
239+
240+
sample_rate = struct.unpack("<I", wav_file.read(4))[0]
241+
# if sample_rate != 44_100 and sample_rate != 48_000:
242+
# raise ValueError(f"WAV sample rate of {sample_rate} invalid. Only 44.1KHz or 48KHz audio are supported")
243+
244+
_ = struct.unpack("<I", wav_file.read(4))[0] # byte_rate
245+
_ = struct.unpack("<H", wav_file.read(2))[0] # block_align
246+
bits_per_sample = struct.unpack("<H", wav_file.read(2))[0]
247+
248+
# usually the sub chunk2 ID ("data") comes next, but
249+
# some online MP3->WAV converters add
250+
# binary data before "data". So, read a fairly large
251+
# block of bytes and search for "data".
252+
253+
binary_block = wav_file.read(200)
254+
offset = binary_block.find(b"data")
255+
if offset == -1:
256+
raise ValueError("WAV sub chunk 2 ID not found")
257+
258+
return (format, sample_rate, bits_per_sample, 44 + offset)
41.5 KB
Binary file not shown.
8.15 KB
Binary file not shown.
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
from machine import Pin, Timer
2+
from audio import WavPlayer
3+
from cosmic import CosmicUnicorn
4+
from picographics import PicoGraphics, DISPLAY_COSMIC_UNICORN as DISPLAY
5+
import time
6+
7+
cu = CosmicUnicorn()
8+
graphics = PicoGraphics(DISPLAY)
9+
10+
amp_enable = Pin(22, Pin.OUT)
11+
amp_enable.on()
12+
13+
graphics.set_font("bitmap6")
14+
WHITE = graphics.create_pen(255, 255, 255)
15+
BLUE = graphics.create_pen(0, 0, 255)
16+
CLEAR = graphics.create_pen(0, 0, 0)
17+
RED = graphics.create_pen(255, 0, 0)
18+
GREEN = graphics.create_pen(0, 255, 0)
19+
cu.set_brightness(0.7)
20+
21+
audio = WavPlayer(0, 10, 11, 9)
22+
23+
24+
class Countdown(object):
25+
def __init__(self):
26+
self.timer_running = False
27+
self.total_seconds = 0
28+
self.timer = None
29+
30+
def process_input(self):
31+
if cu.is_pressed(CosmicUnicorn.SWITCH_VOLUME_UP):
32+
self.total_seconds += 1
33+
if cu.is_pressed(CosmicUnicorn.SWITCH_VOLUME_DOWN):
34+
if self.total_seconds > 0:
35+
self.total_seconds -= 1
36+
if cu.is_pressed(CosmicUnicorn.SWITCH_SLEEP):
37+
self.start_timer()
38+
39+
def display_time(self):
40+
seconds = self.total_seconds % (24 * 3600)
41+
seconds %= 3600
42+
minutes = seconds // 60
43+
seconds %= 60
44+
45+
# Add leading zeros to the minutes and seconds
46+
if len(str(minutes)) == 1:
47+
minutes = "0{}".format(minutes)
48+
if len(str(seconds)) == 1:
49+
seconds = "0{}".format(seconds)
50+
51+
return "{}:{}".format(minutes, seconds)
52+
53+
def draw(self):
54+
graphics.set_pen(graphics.create_pen(0, 0, 0))
55+
graphics.clear()
56+
57+
graphics.set_pen(BLUE)
58+
graphics.circle(0, 0, 12)
59+
graphics.set_pen(GREEN)
60+
graphics.circle(25, 30, 5)
61+
graphics.set_pen(RED)
62+
graphics.circle(0, 32, 12)
63+
64+
graphics.set_pen(CLEAR)
65+
graphics.rectangle(0, 11, CosmicUnicorn.WIDTH, 9)
66+
67+
graphics.set_pen(WHITE)
68+
graphics.text(self.display_time(), 4, 12, -1, 1)
69+
cu.update(graphics)
70+
71+
def start_timer(self):
72+
if not self.timer_running:
73+
self.timer = Timer(mode=Timer.PERIODIC, period=1000, callback=self.countdown)
74+
self.timer_running = True
75+
76+
def reset(self):
77+
self.timer.deinit()
78+
self.timer_running = False
79+
80+
def countdown(self, arg):
81+
82+
if self.total_seconds == 0:
83+
audio.play_wav("doorbell.wav", False)
84+
self.reset()
85+
else:
86+
self.total_seconds -= 1
87+
88+
89+
count = Countdown()
90+
91+
while 1:
92+
count.process_input()
93+
count.draw()
94+
time.sleep(0.07)
52.2 KB
Binary file not shown.

0 commit comments

Comments
 (0)