Native support and integration of Zylia microphones on RaspberryPi platform
e2758a0d8b66d503f1a961989e45446cb69dca49..b40c7292b755d0fc056ccb979488ef452a94a9ad
2 days ago Christophe Weis
Add PythonExample_Recording_Startup.py
b40c72 diff | tree
2 days ago Christophe Weis
feat: add date and time to recording file names
8eb7dc diff | tree
1 files modified
1 files added
117 ■■■■■ changed files
PythonExample_Recording.py 16 ●●●●● patch | view | raw | blame | history
PythonExample_Recording_Startup.py 101 ●●●●● patch | view | raw | blame | history
PythonExample_Recording.py
@@ -1,5 +1,10 @@
import pyaudio
import wave
from datetime import datetime
#  Generate a file name from current date and time
current_date_time = datetime.now().strftime("%Y-%m-%d--%H-%M-%S")
file_name = 'recording_' + current_date_time
# Initialize PyAudio
p = pyaudio.PyAudio()
@@ -15,6 +20,7 @@
device_index = int(input("Please select the device ID to use for recording: "))
n_channels = int(input("Please enter the number of channels to use for recording: "))
duration_sec = int(input("Please enter the desired duration (in seconds) of the recording: "))
#file_name = str(input("Please enter a name for the output file: "))
# Parameters
CHANNELS = n_channels # Number of channels
@@ -22,8 +28,8 @@
CHUNK = 32  # Number of frames per buffer
FORMAT = pyaudio.paInt16 # 16-bit audio
RECORD_SECONDS = duration_sec # Duration to record (in seconds)
OUTPUT_FILENAME = "output.wav"
MONITORING = True # To write to a text file as long as the device is recording
OUTPUT_FILENAME = file_name
MONITORING = False # To write to a text file as long as the device is recording
# Get the chosen device's info to validate it can support the entered number of channels and 48kHz
device_info = p.get_device_info_by_index(device_index)
@@ -52,16 +58,16 @@
for i in range(int(SAMPLE_RATE / CHUNK * RECORD_SECONDS)):
    print (i, f"RECORDING: Check status {stream.is_active()}") # This line is for testing
    print (i, f"RECORDING: Check status {stream.is_active()}") # this line is for testing
    try:
        # Record audio
        # data = stream.read(CHUNK)
        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
        data = stream.read(CHUNK, exception_on_overflow = False) # this line is for testing
        frames.append(data)
        if MONITORING:
            if i%int(10*SAMPLE_RATE/CHUNK) == 0: # Writing current time into "current_recording.txt" every 10 seconds
            if i%int(10*SAMPLE_RATE/CHUNK) == 0: # writing current time into "current_recording.txt" every 10 seconds
                current_second = int(i*CHUNK/SAMPLE_RATE)
                with open('current_recording.txt', 'a') as f:
                    f.write(f"{current_second}\n")
PythonExample_Recording_Startup.py
New file
@@ -0,0 +1,101 @@
import pyaudio
import wave
from datetime import datetime
#  Generate a file name from current date and time
current_date_time = datetime.now().strftime("%Y-%m-%d--%H-%M-%S")
file_name = 'recording_' + current_date_time
# Initialize PyAudio
p = pyaudio.PyAudio()
# No prompts needed for the startup version of this script
'''
# List available input devices
print("Available audio input devices:")
for i in range(p.get_device_count()):
    device_info = p.get_device_info_by_index(i)
    if device_info['maxInputChannels'] > 0:
        print(f"Device ID {i}: {device_info['name']} (Max channels: {device_info['maxInputChannels']})")
# Prompt user to select a device
device_index = int(input("Please select the device ID to use for recording: "))
n_channels = int(input("Please enter the number of channels to use for recording: "))
duration_sec = int(input("Please enter the desired duration (in seconds) of the recording: "))
#file_name = str(input("Please enter a name for the output file: "))
'''
# Parameters
CHANNELS = 19 # Number of channels
SAMPLE_RATE = 48000
CHUNK = 32  # Number of frames per buffer
FORMAT = pyaudio.paInt16 # 16-bit audio
RECORD_SECONDS = 10 # Duration to record (in seconds)
OUTPUT_FILENAME = "/home/rpi1/Desktop/" + file_name + ".wav"
MONITORING = True # To write to a text file as long as the device is recording
# Get the chosen device's info to validate it can support the entered number of channels and 48kHz
device_info = p.get_device_info_by_index(2)
max_channels = device_info['maxInputChannels']
if max_channels < CHANNELS:
    print(f"Error: The selected device only supports {max_channels} channels, but {CHANNELS} channels are required.")
    p.terminate()
    exit(1)
# Open stream
stream = p.open(format=FORMAT,
                channels=CHANNELS,
                rate=SAMPLE_RATE,
                input=True,
                input_device_index=2,
                frames_per_buffer=CHUNK)
print(f"Recording {RECORD_SECONDS} seconds of audio from device ID {2}...")
frames = []
print (f"Check status {stream.is_active()}")
if MONITORING:
    open("/home/rpi1/Desktop/current_recording_" + current_date_time + ".txt","w+")
for i in range(int(SAMPLE_RATE / CHUNK * RECORD_SECONDS)):
    # print (i, f"RECORDING: Check status {stream.is_active()}") # this line is for testing
    try:
        # Record audio
        # data = stream.read(CHUNK)
        data = stream.read(CHUNK, exception_on_overflow = False) # this line is for testing
        frames.append(data)
        if MONITORING:
            if i%int(10*SAMPLE_RATE/CHUNK) == 0: # writing current time into "current_recording.txt" every 10 seconds
                current_second = int(i*CHUNK/SAMPLE_RATE)
                with open('current_recording_' + current_date_time + '.txt', 'a') as f:
                    f.write(f"{current_second}\n")
    except:
        print ("Error")
print("Finished recording.")
print (f"Check status {stream.is_active()}")
# Stop and close the stream
stream.stop_stream()
stream.close()
# Terminate PyAudio
p.terminate()
# Save the recorded audio to a file
wf = wave.open(OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(SAMPLE_RATE)
wf.writeframes(b''.join(frames))
wf.close()
print(f"Audio saved to {OUTPUT_FILENAME}.")