import sounddevice as sdimport numpy as npfrom scipy.io.wavfile import writeimport osimport threading# Configurationsamplerate =44100duration =10# seconds# Devices and labelsmic_devices = {0: "mic",8: "camera"}recordings = {}# Output folderos.makedirs("mic_tests", exist_ok=True)print("ποΈ Starting mic recordings...\n")# Thread worker to record from a micdef record_mic(device_id, name):try:print(f"βΊοΈ Recording from {name} (device {device_id})...") data = sd.rec(int(samplerate * duration), samplerate=samplerate, channels=1, dtype='float32', device=device_id ) sd.wait() # Wait until recording is complete# Save to WAV int16_data = np.clip(data *32767, -32768, 32767).astype(np.int16) write(f"mic_tests/{name}.wav", samplerate, int16_data) recordings[name] = data.flatten()print(f"βοΈ Saved: {name} (device {device_id})")exceptExceptionas e:print(f"β Error with {name} (device {device_id}): {e}")# Start mic recording threadsthreads = []for device_id, name in mic_devices.items(): thread = threading.Thread(target=record_mic, args=(device_id, name)) thread.start() threads.append(thread)# Wait for recordings to finishfor thread in threads: thread.join()print("\nβ All recordings complete.")
ποΈ Starting mic recordings...
βΊοΈ Recording from mic (device 0)...
βΊοΈ Recording from camera (device 8)...
βοΈ Saved: mic (device 0)
βοΈ Saved: camera (device 8)
β All recordings complete.
β You now have a 5-second recording from your default microphone.
π 3. Visualize the Audio Waveform
import plotly.graph_objects as gofrom plotly.subplots import make_subplots# Create subplots for each micfig = make_subplots(rows=len(recordings), cols=1, shared_xaxes=True, vertical_spacing=0.05, subplot_titles=[f"Waveform: {name}"for name in recordings.keys()])# Plot each waveformfor idx, (name, signal) inenumerate(recordings.items(), start=1): fig.add_trace(go.Scatter( y=signal, mode='lines', name=name, line=dict(width=1) ), row=idx, col=1)# Layoutfig.update_layout( height=250*len(recordings), width=1000, title_text="ποΈ Microphone Waveform Comparison", showlegend=False,)fig.update_xaxes(title_text="Samples")fig.update_yaxes(title_text="Amplitude")fig.show()
π 4. Playback in Notebook (Optional)
from IPython.display import Audio, displayprint("π§ Playing back recorded audio...\n")for name in recordings.keys(): filepath =f"mic_tests/{name}.wav"print(f"βΆοΈ {name.capitalize()}") display(Audio(filepath))
π§ Playing back recorded audio...
βΆοΈ Mic
βΆοΈ Camera
Quality Checks
for name, signal in recordings.items(): rms = np.sqrt(np.mean(signal**2)) peak = np.max(np.abs(signal))print(f"{name.capitalize()}: RMS = {rms:.4f}, Peak Amplitude = {peak:.4f}")