Native support and integration of Zylia microphones on RaspberryPi platform
Christophe Weis
13.11.24 3413567dc9db26ecda0100e74821dc78f0f028f8
commit | author | age
96322f 1 import pyaudio
MS 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
17 # Get the chosen device's info to validate it can support 19 channels and 48kHz
18 device_info = p.get_device_info_by_index(device_index)
19 max_channels = device_info['maxInputChannels']
20 if max_channels < 19:
21     print(f"Error: The selected device only supports {max_channels} channels, but 19 channels are required.")
22     p.terminate()
23     exit(1)
24
25 # Parameters
26 CHANNELS = 19
27 SAMPLE_RATE = 48000
28 CHUNK = 2048  # Number of frames per buffer
29 FORMAT = pyaudio.paInt24  # 16-bit audio
30 RECORD_SECONDS = 10  # Duration to record (in seconds)
31 OUTPUT_FILENAME = "output.wav"
32
33 # Open stream
34 stream = p.open(format=FORMAT,
35                 channels=CHANNELS,
36                 rate=SAMPLE_RATE,
37                 input=True,
38                 input_device_index=device_index,
39                 frames_per_buffer=CHUNK)
40
41 print(f"Recording {RECORD_SECONDS} seconds of audio from device ID {device_index}...")
42
43 frames = []
44
45 print (f"Check status {stream.is_active()}")
46
47 for _ in range(int(SAMPLE_RATE / CHUNK * RECORD_SECONDS)):
48
49     try:
50         # Record audio
51         data = stream.read(CHUNK)
52         frames.append(data)
53     except:
54         print ("Error")
55     
56
57 print("Finished recording.")
58
59
60 print (f"Check status {stream.is_active()}")
61 # Stop and close the stream
62 stream.stop_stream()
63 stream.close()
64
65 # Terminate PyAudio
66 p.terminate()
67
68 # Save the recorded audio to a file
69 wf = wave.open(OUTPUT_FILENAME, 'wb')
70 wf.setnchannels(CHANNELS)
71 wf.setsampwidth(p.get_sample_size(FORMAT))
72 wf.setframerate(SAMPLE_RATE)
73 wf.writeframes(b''.join(frames))
74 wf.close()
75
76 print(f"Audio saved to {OUTPUT_FILENAME}.")
77