Okay, let's fix the code to better handle the potential issue with the WH-1000XM4 loopback device and ensure it continues recording the microphone even if the speaker loopback fails due to unsupported format errors like "Invalid number of channels".
The error messages clearly indicate that pyaudio.is_format_supported and likely pyaudio.PyAudio.open are failing for the selected speaker device (WH-1000XM4) when trying various channel counts (2 and 1) at different sample rates. This is a common problem with Bluetooth audio devices or specific drivers; they might not expose a standard loopback input stream, or only support very specific, non-obvious formats.
The current code already tries to handle this by calling test_device_format and setting selected_spk = None if it fails. However, the error messages show that test_device_format itself is logging the individual failures, and there's a redundant print afterward. The p.open call also has retries, which is good, but it seems the fundamental format is unsupported.
The fix will primarily focus on:
- Making the logging clearer when the speaker loopback fails the format test.
- Ensuring the code definitely proceeds with microphone recording even if speaker loopback setup fails completely.
- Slightly adjust
test_device_format logging to be less repetitive.
We cannot force the device/driver to support a format it doesn't expose via PortAudio/PyAudio. The best we can do is detect the failure and continue gracefully.
Here's the modified code:
import threading
import time
import os
import wave
import subprocess
import sys
import shutil
import numpy as np
import pyaudiowpatch as pyaudio
from pystray import Icon, MenuItem, Menu
from PIL import Image, ImageDraw
# --- Globals ---
recording = False
mic_chunks = []
spk_chunks = [] # Added spk_chunks global
sr_mic = None
sr_spk = None # Added sr_spk global
chunk_mic = 8192 # Increased for Bluetooth stability - Note: This chunk size applies to BOTH mic and speaker streams
tray_icon = None
start_time = None
selected_mic = None # Selected microphone device info
selected_spk = None # Selected speaker (loopback) device info
p = None # PyAudio instance for global access
# --- Get available devices ---
def get_available_devices():
global p, selected_mic, selected_spk
if p is None:
p = pyaudio.PyAudio()
input_devices = []
output_devices = [] # These are playback devices, used to find loopback inputs
for i in range(p.get_device_count()):
dev = p.get_device_info_by_index(i)
dev_info = {
'name': dev['name'],
'index': dev['index'],
'input_channels': int(dev['maxInputChannels']), # Keep original reported channels for selection list
'output_channels': int(dev['maxOutputChannels']), # Keep original reported channels for selection list
'sample_rate': int(dev['defaultSampleRate'])
}
# Filter to devices that actually have input or output channels greater than 0
if dev['maxInputChannels'] > 0:
# Limit displayed channels to 2 for common display purposes, but use actual maxInputChannels for testing if needed
input_devices.append({**dev_info, 'display_channels': min(dev_info['input_channels'], 2)})
if 'Razer Seiren Mini' in dev['name'] and not selected_mic:
selected_mic = input_devices[-1] # Default to Razer Seiren Mini
# Use loopback devices provided by pyaudiowpatch for speaker recording selection
if dev['maxOutputChannels'] > 0:
# Check if this output device has a corresponding loopback input
loopback_found = False
for j in range(p.get_device_count()):
loopback_dev = p.get_device_info_by_index(j)
if loopback_dev['name'] == f'Loopback ({dev["name"]})' and loopback_dev['maxInputChannels'] > 0:
loopback_dev_info = {
'name': loopback_dev['name'], # Use the loopback name
'index': loopback_dev['index'],
'input_channels': int(loopback_dev['maxInputChannels']), # Use loopback input channels
'output_channels': 0, # It's an input device for loopback
'sample_rate': int(loopback_dev['defaultSampleRate']),
'original_output_name': dev['name'], # Keep original name for display
'display_channels': min(loopback_dev['maxInputChannels'], 2) # Limit displayed channels
}
output_devices.append(loopback_dev_info)
loopback_found = True
# Default to WH-1000XM4 loopback if found and not selected
if 'WH-1000XM4' in dev['name'] and not selected_spk:
selected_spk = loopback_dev_info
break # Found the loopback device for this output, move to next output device
# If no default mic was found, select the first available input
if not selected_mic and input_devices:
selected_mic = input_devices[0]
# If a previously selected spk is no longer available, reset
if selected_spk:
if not any(dev['index'] == selected_spk['index'] for dev in output_devices):
print(f"⚠️ Previously selected output {selected_spk['name']} no longer available. Resetting to None.")
selected_spk = None
return input_devices, output_devices
# --- Check if device is selected ---
def is_input_selected(device):
return selected_mic and selected_mic['index'] == device['index']
# Need to handle the case where selected_spk is None
def is_output_selected(device):
# Check if the currently selected_spk is None and the device being checked is None (the "None" menu item)
if device is None:
return selected_spk is None
# Check if the currently selected_spk matches the device being checked by index
return selected_spk and selected_spk['index'] == device['index']
# --- Select device ---
def select_input_device(device):
def inner(icon, item):
global selected_mic
selected_mic = device
print(f"🎙️ Selected input: {selected_mic['name']} (Index: {selected_mic['index']})")
# Only update icon title if not recording, or if recording title is generic
if not recording or "Idle" in icon.title or "Saving..." in icon.title:
icon.title = f"Tray Recorder: {selected_mic['name']}"
icon.menu = build_menu() # Rebuild menu with persisted selections
return inner
def select_output_device(device):
def inner(icon, item):
global selected_spk
old_spk_name = selected_spk['name'] if selected_spk else "None"
selected_spk = device
new_spk_name = selected_spk['name'] if selected_spk else "None"
print(f"🔈 Output changed from {old_spk_name} to {new_spk_name} (Index: {selected_spk['index'] if selected_spk else 'N/A'})")
# Only update icon title if not recording, or if recording title is generic
if not recording or "Idle" in icon.title or "Saving..." in icon.title:
icon.title = f"Tray Recorder: {selected_mic['name'] if selected_mic else 'Idle'}"
icon.menu = build_menu() # Rebuild menu with persisted selections
return inner
# --- Build dynamic menu ---
def build_menu():
input_devices, output_devices = get_available_devices()
input_menu = Menu(
*[MenuItem(f"{dev['name']} ({dev['display_channels']} ch, {dev['sample_rate']} Hz)",
select_input_device(dev),
checked=lambda item, dev=dev: is_input_selected(dev))
for dev in input_devices]
)
# Note: output_devices here are actually loopback input devices
output_menu = Menu(
MenuItem("None", select_output_device(None), checked=lambda item: is_output_selected(None)),
*[MenuItem(f"{dev.get('original_output_name', dev['name'])} ({dev['display_channels']} ch, {dev['sample_rate']} Hz)",
select_output_device(dev),
checked=lambda item, dev=dev: is_output_selected(dev))
for dev in output_devices]
)
return Menu(
MenuItem("Select Input Device", input_menu),
MenuItem("Select Output Device (Loopback)", output_menu), # Clarified menu item
MenuItem("Start Recording", start_record, enabled=selected_mic is not None), # Only enable if mic is selected
MenuItem("Stop Recording", stop_record, enabled=recording), # Only enable if recording
MenuItem("Quit", quit_app)
)
# --- Test device format ---
# Returns (supported, actual_channels, actual_sample_rate)
def test_device_format(device, preferred_sample_rate, preferred_channels, is_input=True):
# Try preferred rate/channels first, then common alternatives
# For loopback inputs (is_input=True), we are testing formats SUPPORTED BY THE LOOPBACK DEVICE AS AN INPUT.
# Its capabilities might differ from the original output device's playback capabilities.
sample_rates_to_try = [preferred_sample_rate, 48000, 44100, 32000]
# Start with preferred channels, then try other common input channels (1 or 2)
# Ensure we don't duplicate preferred_channels if it's 1 or 2
channels_to_try = [preferred_channels] + [c for c in [2, 1] if c != preferred_channels]
print(f"🔬 Testing formats for {device['name']} (Input: {is_input}):")
for sr in sample_rates_to_try:
for ch in channels_to_try:
if ch <= 0: continue # Skip testing 0 channels
print(f" Attempting {ch} ch, {sr} Hz...")
try:
p.is_format_supported(
sr,
input_device=device['index'] if is_input else None,
output_device=device['index'] if not is_input else None,
input_channels=ch if is_input else None,
output_channels=ch if not is_input else None,
input_format=pyaudio.paInt16 if is_input else None,
output_format=pyaudio.paInt16 if not is_input else None
)
print(f" ✅ Format supported: {ch} ch, {sr} Hz")
return True, ch, sr
except ValueError as e:
print(f" ⚠️ Format not supported: {ch} ch, {sr} Hz: {e}")
except Exception as e:
print(f" ⚠️ Unexpected error testing format {ch} ch, {sr} Hz: {e}")
# Treat unexpected errors as unsupported format for this test
continue
print(f"❌ No supported format found for {device['name']}.")
return False, 0, preferred_sample_rate # Return False and indicate failure
# --- Audio capture worker ---
def record_worker():
global recording, mic_chunks, spk_chunks, sr_mic, sr_spk, selected_mic, selected_spk, p
print("\n--- Recording Worker Starting ---")
if p is None:
p = pyaudio.PyAudio()
# Log all devices (optional but helpful for debugging)
# print("🔍 Available devices:")
# for i in range(p.get_device_count()):
# dev = p.get_device_info_by_index(i)
# print(f"Device {i}: {dev['name']}, in_ch={dev['maxInputChannels']}, "
# f"out_ch={dev['maxOutputChannels']}, sr={dev['defaultSampleRate']}")
# print("--- End Device List ---")
# --- Microphone Setup ---
if not selected_mic:
print("❌ No microphone selected. Cannot record.")
recording = False
# Terminate PyAudio only if worker is the one that initialized it and is now stopping
if p: p.terminate(); p = None
return
mic_idx = selected_mic['index']
mic_preferred_ch = selected_mic['input_channels']
mic_preferred_sr = selected_mic['sample_rate']
print(f"🎙️ Preparing Microphone: {selected_mic['name']} (Index: {mic_idx})")
mic_supported, mic_actual_ch, sr_mic = test_device_format(selected_mic, mic_preferred_sr, mic_preferred_ch, is_input=True)
if not mic_supported:
print(f"❌ Microphone format not supported after testing. Cannot record.")
recording = False
if p: p.terminate(); p = None
return
print(f"🎙️ Using Microphone: {selected_mic['name']} "
f"(Index: {mic_idx}, Channels: {mic_actual_ch}, Sample Rate: {sr_mic} Hz)")
mic_stream = None
try:
mic_stream = p.open(
format=pyaudio.paInt16,
channels=mic_actual_ch,
rate=sr_mic,
input=True,
input_device_index=mic_idx,
frames_per_buffer=chunk_mic
)
print("✅ Microphone stream opened.")
except Exception as e:
print(f"❌ Cannot open microphone stream {selected_mic['name']}: {e}")
recording = False
if p: p.terminate(); p = None
return
# --- Speaker Loopback Setup (if selected) ---
spk_stream = None
spk_actual_ch = None # Actual channels used by the stream if opened
spk_is_active = False # Flag to track if speaker recording is actually enabled
if selected_spk:
print(f"🔈 Preparing Speaker Loopback: {selected_spk['name']} (Index: {selected_spk['index']})")
print("⚠️ Note: Bluetooth device loopback (like WH-1000XM4) may be unreliable or unsupported.")
spk_idx = selected_spk['index']
# When getting device info, output_channels refers to the *original* playback device.
# For loopback, we need the maxInputChannels of the loopback device itself.
# We stored this in selected_spk['input_channels'] during device enumeration.
spk_preferred_ch = selected_spk['input_channels'] # Use the input channels of the loopback device
spk_preferred_sr = selected_spk['sample_rate']
spk_supported, spk_actual_ch, sr_spk = test_device_format(selected_spk, spk_preferred_sr, spk_preferred_ch, is_input=True)
if not spk_supported:
print(f"❌ Speaker loopback format not supported after testing. Disabling speaker recording.")
selected_spk = None # Explicitly disable loopback if format test fails
spk_is_active = False # Ensure flag is false
else:
print(f"🔈 Using Speaker Loopback: {selected_spk['name']} "
f"(Index: {spk_idx}, Channels: {spk_actual_ch}, Sample Rate: {sr_spk} Hz)")
# Attempt to open speaker stream with retries
for attempt in range(5):
try:
spk_stream = p.open(
format=pyaudio.paInt16,
channels=spk_actual_ch, # Use the actual channels found by test_device_format
rate=sr_spk, # Use the actual rate found by test_device_format
input=True,
input_device_index=spk_idx,
frames_per_buffer=chunk_mic # Use the same buffer size as mic for simpler processing
)
print(f"✅ Speaker stream opened on attempt {attempt + 1}.")
spk_is_active = True # Successfully opened stream
break # Exit retry loop
except Exception as e:
print(f"⚠️ Attempt {attempt + 1} failed to open speaker stream {selected_spk['name']}: {e}")
time.sleep(1.0) # Longer delay for flaky devices
if attempt == 4:
print("❌ Cannot open speaker stream after 5 attempts. Disabling speaker recording.")
selected_spk = None # Ensure it's None
spk_is_active = False # Ensure flag is false
if not spk_is_active:
print("🔈 Speaker loopback recording is disabled.")
# --- Capture Loop ---
mic_chunks.clear()
spk_chunks.clear() # Clear speaker chunks regardless of whether stream was opened
loop_count = 0
# No timeout anymore, rely on recording=False or errors
print("🔄 Starting capture loop...")
while recording:
loop_count += 1
# print(f"🔄 Loop iteration {loop_count}") # Keep this print for debugging if needed, but can be noisy
try:
# --- Microphone Capture ---
if mic_stream and mic_stream.is_active():
try:
# Read data with a small timeout to avoid blocking indefinitely
data_mic = mic_stream.read(chunk_mic, exception_on_overflow=False, timeout=0.1)
if data_mic:
arr_mic = np.frombuffer(data_mic, dtype=np.int16)
# Reshape only if mic_actual_ch > 0
if mic_actual_ch > 0:
arr_mic = arr_mic.reshape(-1, mic_actual_ch)
# Convert to mono by averaging channels if stereo
if mic_actual_ch > 1:
mono_mic = arr_mic.mean(axis=1).astype(np.int16).tobytes()
else:
# If already mono (1 channel), just use the data directly
mono_mic = data_mic
mic_chunks.append(mono_mic)
# Optional: Amplitude check for debugging
# mic_max = np.max(np.abs(arr_mic)) if arr_mic.size > 0 else 0
# print(f"🎙️ Mic chunk {len(mic_chunks)}, max amplitude: {mic_max}")
else:
print("⚠️ Mic stream reported 0 channels. Skipping data processing.")
else:
# print(f"⚠️ Empty data from {selected_mic['name']} read.") # Can be normal during silence
pass # Allow empty reads, don't print warning every time
except Exception as e:
# Catch potential read errors, especially with devices disconnecting
print(f"⚠️ Mic read error: {e}. Attempting to reinitialize mic stream.")
try:
if mic_stream: mic_stream.close()
mic_stream = p.open(
format=pyaudio.paInt16,
channels=mic_actual_ch,
rate=sr_mic,
input=True,
input_device_index=mic_idx,
frames_per_buffer=chunk_mic
)
print(f"🎙️ Mic stream reinitialized successfully.")
except Exception as reinit_e:
print(f"❌ Failed to reinitialize mic stream: {reinit_e}")
recording = False # Critical error, stop recording
break # Exit capture loop
else:
# This could happen if is_active() returns False
print(f"⚠️ Mic stream is not active. Stopping recording.")
recording = False
break # Exit capture loop
# --- Speaker Capture (if active) ---
if spk_is_active and spk_stream and spk_stream.is_active():
try:
# Read data with a small timeout
data_spk = spk_stream.read(chunk_mic, exception_on_overflow=False, timeout=0.1)
if data_spk:
arr_spk = np.frombuffer(data_spk, dtype=np.int16)
# Reshape only if spk_actual_ch > 0
if spk_actual_ch > 0:
arr_spk = arr_spk.reshape(-1, spk_actual_ch)
# Convert to mono by averaging channels if stereo
if spk_actual_ch > 1:
mono_spk = arr_spk.mean(axis=1).astype(np.int16).tobytes()
else:
# If already mono (1 channel), just use the data directly
mono_spk = data_spk
spk_chunks.append(mono_spk)
# Optional: Amplitude check for debugging
# spk_max = np.max(np.abs(arr_spk)) if arr_spk.size > 0 else 0
# print(f"🔈 Speaker chunk {len(spk_chunks)}, max amplitude: {spk_max}")
else:
print("⚠️ Speaker stream reported 0 channels. Skipping data processing.")
else:
# print(f"⚠️ Empty data from {selected_spk['name']} read.") # Can be normal during silence
pass # Allow empty reads
except Exception as e:
# Catch potential read errors, especially with devices disconnecting
print(f"⚠️ Speaker read error: {e}. Attempting to reinitialize speaker stream.")
try:
if spk_stream: spk_stream.close()
spk_stream = p.open(
format=pyaudio.paInt16,
channels=spk_actual_ch,
rate=sr_spk,
input=True,
input_device_index=spk_idx, # Use spk_idx which was set if spk_is_active is True
frames_per_buffer=chunk_mic
)
print(f"🔈 Speaker stream reinitialized successfully.")
spk_is_active = True # Re-confirm active state
except Exception as reinit_e:
print(f"❌ Failed to reinitialize speaker stream: {reinit_e}")
print("🔈 Disabling speaker recording.")
spk_stream = None # Ensure stream object is None
selected_spk = None # Ensure selected_spk is None
spk_is_active = False # Disable flag
# Continue recording mic
# Small sleep to prevent 100% CPU usage
time.sleep(0.005) # Shorter sleep than before
except Exception as e:
# Catch any other unexpected errors in the loop
print(f"⚠️ Unexpected error in capture loop: {e}")
recording = False
break # Exit capture loop
print(f"🛑 Capture loop exited (reason: {'recording=False' if not recording else 'Unknown Error'}, "
f"mic_chunks: {len(mic_chunks)}, spk_chunks: {len(spk_chunks) if spk_is_active else 0}, loops: {loop_count})")
# Cleanup streams (done outside the loop after recording=False)
if mic_stream:
try:
if mic_stream.is_active():
mic_stream.stop_stream()
mic_stream.close()
print("✅ Microphone stream closed.")
except Exception as e:
print(f"⚠️ Error closing mic stream: {e}")
if spk_stream:
try:
if spk_stream.is_active():
spk_stream.stop_stream()
spk_stream.close()
print("✅ Speaker stream closed.")
except Exception as e:
print(f"⚠️ Error closing speaker stream: {e}")
# Terminate PyAudio if the worker is the one that initialized it
if p:
try:
p.terminate()
print("✅ PyAudio terminated.")
except Exception as e:
print(f"⚠️ Error terminating PyAudio: {e}")
p = None # Reset global p after terminating
print("--- Recording Worker Exited ---")
# --- Save & mix via ffmpeg ---
def save_recording():
global mic_chunks, spk_chunks, sr_mic, sr_spk, selected_mic, selected_spk
print("\n--- Saving Recording ---")
mic_available = len(mic_chunks) > 0
spk_available = len(spk_chunks) > 0
print(f"💾 Preparing to save: {len(mic_chunks)} mic chunks ({selected_mic['name'] if selected_mic else 'N/A'}), "
f"{len(spk_chunks)} speaker chunks ({selected_spk['original_output_name'] if selected_spk else 'N/A'})")
if not mic_available and not spk_available:
print("❌ No audio recorded—skipping save.")
return
# Check for silence *after* recording stops
mic_silent = True
mic_data = b"".join(mic_chunks)
if mic_data:
mic_np_data = np.frombuffer(mic_data, dtype=np.int16)
mic_max = np.max(np.abs(mic_np_data)) if mic_np_data.size > 0 else 0
# Consider audio silent if max amplitude is very low
mic_silent = mic_max < 100 # Increased threshold slightly
print(f"🎙️ Mic audio max amplitude: {mic_max}")
spk_silent = True
spk_data = b"".join(spk_chunks)
if spk_data:
spk_np_data = np.frombuffer(spk_data, dtype=np.int16)
spk_max = np.max(np.abs(spk_np_data)) if spk_np_data.size > 0 else 0
# Consider audio silent if max amplitude is very low
spk_silent = spk_max < 100 # Increased threshold slightly
print(f"🔈 Speaker audio max amplitude: {spk_max}")
if (mic_available and mic_silent) and (spk_available and spk_silent or not spk_available):
# Only skip if mic was recorded AND silent, AND speaker wasn't recorded OR was recorded and silent
print("❌ Audio is silent—skipping save.")
return
ts = int(time.time())
timestamp_str = time.strftime('%Y%m%d_%H%M%S')
wav_files = []
# Save microphone audio if recorded and not silent
if mic_available and not mic_silent:
wav_mic = f"recording_mic_{timestamp_str}.wav"
try:
with wave.open(wav_mic, "wb") as wf:
wf.setnchannels(1) # Mono
wf.setsampwidth(2) # 16-bit = 2 bytes
wf.setframerate(sr_mic if sr_mic else 44100) # Use detected rate, default if needed
wf.writeframes(mic_data)
wav_files.append(wav_mic)
print(f"✅ Saved temporary WAV: {wav_mic}")
except Exception as e:
print(f"❌ Error saving mic WAV: {e}")
# Save speaker audio if recorded and not silent
if spk_available and not spk_silent:
wav_spk = f"recording_spk_{timestamp_str}.wav"
try:
with wave.open(wav_spk, "wb") as wf:
wf.setnchannels(1) # Mono
wf.setsampwidth(2) # 16-bit = 2 bytes
wf.setframerate(sr_spk if sr_spk else 44100) # Use detected rate, default if needed
wf.writeframes(spk_data)
wav_files.append(wav_spk)
print(f"✅ Saved temporary WAV: {wav_spk}")
except Exception as e:
print(f"❌ Error saving speaker WAV: {e}")
if not wav_files:
print("❌ No non-silent audio files to process.")
# Clear chunks even if not saved
mic_chunks.clear()
spk_chunks.clear()
return
# Check for ffmpeg
ffmpeg_path = shutil.which("ffmpeg")
if ffmpeg_path is None:
# Try local ffmpeg.exe in script directory
script_dir = os.path.dirname(os.path.abspath(__file__))
local_ffmpeg = os.path.join(script_dir, "ffmpeg.exe")
if os.path.exists(local_ffmpeg):
ffmpeg_path = local_ffmpeg
else:
print("❌ FFmpeg not found. Cannot convert to MP3.")
print(" Please install FFmpeg and add it to your system PATH, or place ffmpeg.exe")
print(f" in the script directory: {script_dir}")
print("✅ Audio saved as WAV file(s):")
for wf in wav_files:
print(f" - {wf}")
# Clear chunks even if not converted to MP3
mic_chunks.clear()
spk_chunks.clear()
return
out_mp3 = f"recording_{timestamp_str}.mp3"
# Build FFmpeg command
try:
if len(wav_files) == 1:
# Just convert the single WAV to MP3
cmd = [ffmpeg_path, "-y", "-i", wav_files[0], "-codec:a", "libmp3lame", "-qscale:a", "2", out_mp3]
print(f"ℹ️ Converting single WAV to MP3: {' '.join(cmd)}")
else:
# Mix two WAV files (mic and speaker) into a single stereo MP3
# Use -filter_complex amix=inputs=2 to mix them.
# Need to ensure they have the same sample rate for amix.
# If sample rates differ, resample one or both using afade or similar.
# For simplicity, let's assume they are close enough or handle resampling later if needed.
# The current capture logic uses the device's reported SR, which might differ.
# Let's resample them both to 44100 Hz for mixing robustness.
# Input streams: [0:a] is first input's audio, [1:a] is second.
# Need to add aresample filter for each input before amix.
cmd = [ffmpeg_path, "-y"]
for i, wav in enumerate(wav_files):
cmd.extend(["-i", wav])
# Filter complex for resampling and mixing
# [0:a]resample=44100[a0]; [1:a]resample=44100[a1]; [a0][a1]amix=inputs=2:duration=longest
# Output is 2 channels because amix outputs sum of inputs, and inputs are mono but combined
# If we want stereo output (mic on left, spk on right), need a different filter:
# [0:a]channelsplit=channel_map.L=M [mic_l]; [1:a]channelsplit=channel_map.R=M [spk_r]; [mic_l][spk_r]amerge=inputs=2
# Let's go with simple mixing for now, resulting in a single mono track if both were mono.
# If the goal is a stereo file (mic left, speaker right), the amix filter is insufficient.
# A more complex filter is needed:
# "[0:a]format=s16p,aresample=resampler=sinc:osr=44100[a0];[1:a]format=s16p,aresample=resampler=sinc:osr=44100[a1];[a0][a1]amerge=inputs=2[a]"
# then map "[a]" to the output.
# Let's stick to the simpler amix for a single output channel, which seems more likely for voice recording mix.
# To be safe with sample rates: add aresample to a common rate (e.g., 44100 or max of inputs)
# Let's resample both to the highest sample rate found (either sr_mic or sr_spk, or 44100 if unknown)
target_sr = 44100 # Default target SR for mixing
if sr_mic and sr_spk:
target_sr = max(sr_mic, sr_spk)
elif sr_mic:
target_sr = sr_mic
elif sr_spk:
target_sr = sr_spk
filter_complex_parts = []
input_streams = []
for i in range(len(wav_files)):
# Resample each input stream to the target sample rate
filter_complex_parts.append(f"[{i}:a]aresample={target_sr}[a{i}]")
input_streams.append(f"[a{i}]")
# Amix the resampled streams
amix_filter = f"{''.join(input_streams)}amix=inputs={len(wav_files)}:duration=longest[aout]"
filter_complex_parts.append(amix_filter)
cmd.extend(["-filter_complex", ";".join(filter_complex_parts), "-map", "[aout]", "-codec:a", "libmp3lame", "-qscale:a", "2", out_mp3])
print(f"ℹ️ Mixing WAVs to MP3: {' '.join(cmd)}")
# Run FFmpeg command
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"✅ Saved: {out_mp3}")
# Clean up WAV files after successful MP3 conversion
for wf in wav_files:
try:
os.remove(wf)
print(f"🗑️ Removed temporary WAV: {wf}")
except OSError as e:
print(f"⚠️ Could not delete temporary WAV file {wf}: {e}")
except (subprocess.CalledProcessError, FileNotFoundError) as e:
print(f"❌ FFmpeg failed: {e}")
print("✅ Keeping temporary WAV file(s):")
for wf in wav_files:
print(f" - {wf}")
except Exception as e:
print(f"❌ An unexpected error occurred during saving: {e}")
# Always clear chunks after save attempt (successful or not)
mic_chunks.clear()
spk_chunks.clear()
print("--- Saving Recording Finished ---")
# --- Tray & Ctrl+C handling ---
def make_icon_image(is_rec=False):
# Use a simple PIL image for the icon
img = Image.new("RGB", (64, 64), color=(0, 0, 0, 0)) # Transparent background
d = ImageDraw.Draw(img)
# Draw a circle or square
if is_rec:
# Red circle for recording
d.ellipse((8, 8, 56, 56), fill="red")
else:
# Grey circle for idle
d.ellipse((8, 8, 56, 56), fill="grey")
return img
def start_record(icon, item):
global recording, start_time, tray_icon # Use global tray_icon
if recording:
print("ℹ️ Recording is already active.")
return
if not selected_mic:
print("❌ Please select a microphone first.")
# Update menu to show Start is disabled
tray_icon.menu = build_menu()
return
print("▶ Starting recording...")
recording = True
start_time = time.time()
# Start the worker thread
threading.Thread(target=record_worker, daemon=True).start()
# Update icon and title
tray_icon.icon = make_icon_image(True)
tray_icon.title = f"Recording: {selected_mic['name']}"
tray_icon.menu = build_menu() # Update menu (Stop becomes enabled)
def stop_record(icon=None, item=None):
global recording, start_time, tray_icon # Use global tray_icon
if not recording:
print("ℹ️ Recording is not active.")
return
elapsed = time.time() - start_time if start_time else 0
# Optional: Prevent stopping very short recordings
# if elapsed < 3: # Reduced threshold slightly
# print(f"⚠️ Stop ignored: recording too short ({elapsed:.1f}s < 3s)")
# return
print(f"🛑 Stop record called (elapsed: {elapsed:.1f}s)")
# Set recording flag to False - this signals the worker thread to stop its loop
recording = False
# Update icon and title immediately
if tray_icon:
tray_icon.icon = make_icon_image(False)
tray_icon.title = "Stopping & Saving..."
# The menu will be rebuilt by build_menu after saving
# save_recording is called *after* the worker thread finishes because
# it needs the mic_chunks and spk_chunks which are populated by the worker.
# The worker loop exits when `recording` becomes False.
# We could wait for the worker thread to join here, but that would block the UI thread.
# A simpler approach for a daemon thread is to let it finish on its own,
# and save_recording is called implicitly after the worker exits.
# However, the current structure calls save_recording *right after* setting recording=False.
# This is problematic if the worker hasn't finished processing the last chunks.
# Let's modify save_recording to be called *by the worker* before it terminates, OR
# make the main thread wait for the worker. Waiting is safer.
# Let's adjust: the worker should *not* terminate PyAudio.
# The main thread or a dedicated cleanup function should terminate PyAudio and save.
# Simpler: worker sets a flag like `worker_done = True` and main thread checks,
# or worker calls the save function directly. Let's have the worker call save.
# --- Refined Stop Logic ---
# 1. Set `recording = False`.
# 2. Worker loop checks `recording` and exits.
# 3. Worker performs cleanup (closes streams).
# 4. Worker calls `save_recording()`.
# 5. Worker terminates PyAudio instance.
# 6. Worker thread naturally ends.
# So, `stop_record` only needs to set the flag and update the UI.
# The `save_recording` call and PyAudio termination will happen in the worker.
# Rebuild menu after setting recording=False so Start is enabled again once worker exits
# (handled by save_recording calling build_menu) - wait, no, build_menu needs pyaudio.
# Let's keep PyAudio initialization/termination outside the worker, and have
# save_recording wait for the worker.
# --- Alternative Stop Logic ---
# 1. Set `recording = False`.
# 2. Worker loop checks `recording` and exits, cleaning up streams but *not* PyAudio.
# 3. `stop_record` waits for worker thread to finish.
# 4. `stop_record` calls `save_recording`.
# 5. `stop_record` terminates PyAudio.
# 6. `stop_record` updates UI menu.
# This seems better. We need a way to track the worker thread.
global worker_thread
if worker_thread and worker_thread.is_alive():
print("⏳ Waiting for recording worker to finish...")
# The worker loop should exit quickly after `recording` is False
worker_thread.join(timeout=10) # Wait up to 10 seconds
# Ensure PyAudio is terminated after potential save
global p
if p:
try:
p.terminate()
print("✅ PyAudio terminated by stop_record.")
except Exception as e:
print(f"⚠️ Error terminating PyAudio: {e}")
p = None # Reset global p
# Save the recorded chunks *after* the worker has stopped populating them
save_recording()
# Rebuild menu and update title after saving is complete
if tray_icon:
tray_icon.title = f"Tray Recorder: {selected_mic['name'] if selected_mic else 'Idle'}"
tray_icon.menu = build_menu() # Update menu (Stop becomes disabled, Start potentially enabled)
# Global variable to hold the worker thread
worker_thread = None
# --- Main ---
if __name__ == "__main__":
# Initialize tray icon
# Ensure we have a PyAudio instance to build the initial menu
if p is None:
p = pyaudio.PyAudio() # Initialize PyAudio in main thread
# Find initial default devices
# get_available_devices() already selects defaults
tray_icon = Icon(
"TrayRecorder",
icon=make_icon_image(False),
title=f"Tray Recorder: {selected_mic['name'] if selected_mic else 'Idle'}" # Set initial title based on default mic
)
# Set initial menu
tray_icon.menu = build_menu()
# Start the tray icon thread
tray_icon.run_detached()
print("Tray recorder running. Use tray menu to select devices and Start/Stop, or Ctrl+C to quit.")
# In the main loop, we just keep the script alive and handle Ctrl+C
try:
while True:
time.sleep(1) # Keep main thread alive
except KeyboardInterrupt:
print("\nInterrupted; stopping...")
# Call stop_record to handle cleanup and saving
stop_record()
# Stop the tray icon
if tray_icon:
tray_icon.stop()
# Ensure PyAudio is terminated if it wasn't already
if p:
try:
p.terminate()
print("✅ PyAudio terminated by KeyboardInterrupt handler.")
except Exception as e:
print(f"⚠️ Error terminating PyAudio during exit: {e}")
p = None
sys.exit(0)