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}")