-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmic_serial.py
More file actions
54 lines (45 loc) · 1.57 KB
/
Copy pathmic_serial.py
File metadata and controls
54 lines (45 loc) · 1.57 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
import serial
import wave
import struct
# Serial port configuration
PORT = '/dev/cu.usbmodem00F1F5FF3' # Change this to your serial port
BAUD_RATE = 1000000 # Change this to your baud rate
CHUNK_SIZE = 1024 # Number of bytes to read at a time
TIMEOUT = 1
# WAV file configuration
SAMPLE_RATE = 16000 # Change this to your desired sample rate
CHANNELS = 1
SAMPLE_WIDTH = 2 # 16-bit
def main():
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE, timeout=TIMEOUT)
print(f"Connected to {PORT}")
# Kill inferencer
ser.write('b'.encode('utf-8'))
while True:
data = ser.readline()
if data: break
# Open WAV file for writing
with wave.open('output.wav', 'wb') as wav_file:
wav_file.setnchannels(CHANNELS)
wav_file.setsampwidth(SAMPLE_WIDTH)
wav_file.setframerate(SAMPLE_RATE)
try:
while True:
# Read data from serial port
data = ser.read(CHUNK_SIZE) # Read 1024 bytes at a time
if not data:
break
# received odd number of bytes
if (len(data) % 2) != 0:
data = data[:-1]
# 16-bit signed PCM samples (big endian)
samples = struct.unpack(f'>{len(data)//2}h', data)
# convert to little endian
wav_file.writeframes(struct.pack(f'<{len(samples)}h', *samples))
except KeyboardInterrupt:
print("Recording stopped")
finally:
ser.close()
print("Serial port closed")
main()