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