-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
88 lines (68 loc) · 2.22 KB
/
example.py
File metadata and controls
88 lines (68 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import array
import sys
from board import make_display, make_mic, make_speaker, make_touch, mount_sd
from cst8xx import CST8XX
from machine import I2S
from st77916 import ST77916
SAMPLE_RATE = 16_000
RECORD = 0
PLAY = 1
AUDIO_FILE = "/sd/audio.raw"
def record(mic: I2S):
with open(AUDIO_FILE, "wb") as audio_file:
buffer = array.array("h", [0] * 1000)
for _ in range(32):
mic.readinto(buffer)
audio_file.write(buffer)
def play(spkr: I2S):
with open(AUDIO_FILE, "rb") as audio_file:
buffer = array.array("h", [0] * 1000)
for _ in range(32):
audio_file.readinto(buffer)
spkr.write(buffer)
def update_ui(display: ST77916, ts: CST8XX):
def in_box(touch, box):
if (touch[0] > box[0] and touch[0] < (box[0] + box[2]) and
touch[1] > box[1] and touch[1] < (box[1] + box[3])):
return True
return False
record_box = (50, 150, 60, 60)
play_box = (250, 150, 60, 60)
display.fill(display.rgb(50, 50, 50))
display.rect(*record_box, display.rgb(128, 0, 0))
display.text("Record", record_box[0], (record_box[1] + record_box[3] + 2))
display.rect(*play_box, display.rgb(0, 0, 128))
display.text("Play", play_box[0], (play_box[1] + play_box[3] + 2))
result = None
if point := ts.points:
if in_box(point, record_box):
print("record")
display.rect(*record_box, display.rgb(128, 0, 0), True)
result = RECORD
elif in_box(point, play_box):
print("play")
display.rect(*play_box, display.rgb(0, 0, 128), True)
result = PLAY
display.show()
return result
def main():
try:
mount_sd("/sd")
except OSError as e:
print(f"Ensure a FAT formatted SD card is inserted: OSError {e}")
sys.exit(1)
spkr = make_speaker(1, 16, SAMPLE_RATE)
mic = make_mic(SAMPLE_RATE)
display = make_display()
ts = make_touch()
try:
while True:
if (pressed := update_ui(display, ts)) == RECORD:
record(mic)
elif pressed == PLAY:
play(spkr)
except KeyboardInterrupt:
pass
finally:
display.deinit()
main()