diff --git a/client_python.py b/client_python.py index 570fd86c..da762d57 100644 --- a/client_python.py +++ b/client_python.py @@ -161,6 +161,9 @@ async def run_file(args): sys.exit(1) audio, sr = sf.read(args.file) + # soundfile returns (frames, channels), librosa resamples the last axis + if audio.ndim > 1: + audio = audio[:, 0] if sr != SAMPLE_RATE: try: import librosa @@ -168,8 +171,6 @@ async def run_file(args): except ImportError: print(f"Audio is {sr}Hz, need 16kHz. Install librosa: pip install librosa") sys.exit(1) - if audio.ndim > 1: - audio = audio[:, 0] audio = audio.astype(np.float32) duration = len(audio) / SAMPLE_RATE diff --git a/client_test.py b/client_test.py index 70e56be6..9c61acb4 100644 --- a/client_test.py +++ b/client_test.py @@ -33,6 +33,9 @@ def load_audio(file_path): audio, sr = sf.read(file_path) + # soundfile returns (frames, channels), librosa resamples the last axis + if audio.ndim > 1: + audio = audio[:, 0] if sr != SAMPLE_RATE: try: import librosa @@ -40,8 +43,6 @@ def load_audio(file_path): except ImportError: print(f"ERROR: Audio is {sr}Hz. Install librosa for resampling.") sys.exit(1) - if audio.ndim > 1: - audio = audio[:, 0] return audio.astype(np.float32) diff --git a/tests/test_streaming_client_collection.py b/tests/test_streaming_client_collection.py index 67a27ada..455b29ea 100644 --- a/tests/test_streaming_client_collection.py +++ b/tests/test_streaming_client_collection.py @@ -10,12 +10,14 @@ import sys import wave +import numpy as np import pytest from websockets.legacy.server import serve ROOT = Path(__file__).resolve().parents[1] CLIENT = ROOT / "client_test.py" +PYTHON_CLIENT = ROOT / "client_python.py" @pytest.mark.parametrize("import_mode", ["prepend", "append", "importlib"]) @@ -104,3 +106,56 @@ async def handler(ws, path=None): assert ("RESULTS: 0 passed, 3 failed" if missing_final else "RESULTS: 3 passed, 0 failed") in output assert sessions == ([pcm, b"\0" * 1600, pcm] if missing_final else [pcm, b"\0" * 1600, pcm, pcm]) assert received_hotwords == ([hotwords] if hotwords else []) + + +@pytest.mark.parametrize("client", [CLIENT, PYTHON_CLIENT], ids=lambda path: path.name) +@pytest.mark.parametrize("sample_rate", [8000, 16000, 44100]) +def test_clients_send_one_channel_of_stereo_audio_at_16khz(tmp_path, client, sample_rate): + pytest.importorskip("librosa") + audio_path = tmp_path / "stereo.wav" + tone = np.sin(2 * np.pi * 440 * np.arange(sample_rate) / sample_rate) * 12000 + with wave.open(str(audio_path), "wb") as audio: + audio.setnchannels(2) + audio.setsampwidth(2) + audio.setframerate(sample_rate) + audio.writeframes(np.column_stack([tone, np.zeros_like(tone)]).astype("