Native support and integration of Zylia microphones on RaspberryPi platform
Christophe Weis
06.12.24 e2758a0d8b66d503f1a961989e45446cb69dca49
commit | author | age
e39781 1 import pyaudio
CW 2 import wave
3
4 # Initialize PyAudio
5 p = pyaudio.PyAudio()
6
7 # List available input devices
8 print("Available audio input devices:")
9 for i in range(p.get_device_count()):
10     device_info = p.get_device_info_by_index(i)
11     if device_info['maxInputChannels'] > 0:
12         print(f"Device ID {i}: {device_info['name']} (Max channels: {device_info['maxInputChannels']})")
13
14 # Prompt user to select a device
15 device_index = int(input("Please select the device ID to use for recording: "))
16 n_channels = int(input("Please enter the number of channels to use for recording: "))
17 duration_sec = int(input("Please enter the desired duration (in seconds) of the recording: "))
18
19 # Parameters
20 CHANNELS = n_channels # Number of channels
21 SAMPLE_RATE = 48000
22 CHUNK = 32  # Number of frames per buffer
23 FORMAT = pyaudio.paInt16 # 16-bit audio
24 RECORD_SECONDS = duration_sec # Duration to record (in seconds)
25 OUTPUT_FILENAME = "output.wav"
26 MONITORING = True # To write to a text file as long as the device is recording
27
28 # Get the chosen device's info to validate it can support the entered number of channels and 48kHz
29 device_info = p.get_device_info_by_index(device_index)
30 max_channels = device_info['maxInputChannels']
31 if max_channels < CHANNELS:
32     print(f"Error: The selected device only supports {max_channels} channels, but {CHANNELS} channels are required.")
33     p.terminate()
34     exit(1)
35
36 # Open stream
37 stream = p.open(format=FORMAT,
38                 channels=CHANNELS,
39                 rate=SAMPLE_RATE,
40                 input=True,
41                 input_device_index=device_index,
42                 frames_per_buffer=CHUNK)
43
44 print(f"Recording {RECORD_SECONDS} seconds of audio from device ID {device_index}...")
45
46 frames = []
47
48 print (f"Check status {stream.is_active()}")
49
50 if MONITORING:
51     open("current_recording.txt","w+")
52
53 for i in range(int(SAMPLE_RATE / CHUNK * RECORD_SECONDS)):
54
55     print (i, f"RECORDING: Check status {stream.is_active()}") # This line is for testing
56
57     try:
58         # Record audio
59         # data = stream.read(CHUNK)
60         data = stream.read(CHUNK, exception_on_overflow = False) # This line (as an alternative to the line above) is to prevent overflows from terminating the recording
61         frames.append(data)
62
63         if MONITORING:
64             if i%int(10*SAMPLE_RATE/CHUNK) == 0: # Writing current time into "current_recording.txt" every 10 seconds
65                 current_second = int(i*CHUNK/SAMPLE_RATE)
66                 with open('current_recording.txt', 'a') as f:
67                     f.write(f"{current_second}\n")
68     
69     except:
70         print ("Error")
71
72 print("Finished recording.")
73
74
75 print (f"Check status {stream.is_active()}")
76 # Stop and close the stream
77 stream.stop_stream()
78 stream.close()
79
80 # Terminate PyAudio
81 p.terminate()
82
83 # Save the recorded audio to a file
84 wf = wave.open(OUTPUT_FILENAME, 'wb')
85 wf.setnchannels(CHANNELS)
86 wf.setsampwidth(p.get_sample_size(FORMAT))
87 wf.setframerate(SAMPLE_RATE)
88 wf.writeframes(b''.join(frames))
89 wf.close()
90
91 print(f"Audio saved to {OUTPUT_FILENAME}.")
92