Skip to content

πŸŽ› πŸ”Š A Python library for audio.

Add explicit error message when swapping the samplerate and num_channels parameters on WriteableAudioFile. (#238)

Peter Sobot5495f00f870f
diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.h
index 47d21be..f2cf57a 100644
--- a/pedalboard/io/WriteableAudioFile.h
+++ b/pedalboard/io/WriteableAudioFile.h
@@ -234,7 +234,7 @@ public:
pybind11::gil_scoped_release release;
if (!isInteger(writeSampleRate)) {
- throw std::domain_error(
+ throw py::type_error(
"Opening an audio file for writing requires an integer sample rate.");
}
@@ -244,8 +244,22 @@ public:
}
if (numChannels == 0) {
- throw py::type_error("Opening an audio file for writing requires a "
- "non-zero num_channels.");
+ throw std::domain_error("Opening an audio file for writing requires a "
+ "non-zero num_channels.");
+ }
+
+ // Tiny quality-of-life improvement to try to detect if people have swapped
+ // the num_channels and samplerate arguments:
+ if ((numChannels == 48000 || numChannels == 44100 || numChannels == 22050 ||
+ numChannels == 11025) &&
+ writeSampleRate < 8000) {
+ throw std::domain_error(
+ "Arguments of num_channels=" + std::to_string(numChannels) +
+ " and samplerate=" + std::to_string(writeSampleRate) +
+ " were provided when opening a file for writing. These arguments "
+ "appear to be flipped, and may cause an invalid audio file to be "
+ "written. Try reversing the order of the samplerate "
+ "and num_channels arguments.");
}
registerPedalboardAudioFormats(formatManager, true);
diff --git a/tests/test_io.py b/tests/test_io.py
index 0b7a630..22c1b5f 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -719,7 +719,7 @@ def test_write_twice_overwrites(
@pytest.mark.parametrize("samplerate", [1234.5, 23.0000000001])
def test_fractional_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):
filename = str(tmp_path / f"test{extension}")
- with pytest.raises(ValueError):
+ with pytest.raises(TypeError):
pedalboard.io.WriteableAudioFile(filename, samplerate=samplerate, num_channels=1)
@@ -755,6 +755,17 @@ def test_sample_rate_is_int_by_default(samplerate: int):
assert f.samplerate == samplerate
[email protected]("extension", [".flac"])
[email protected]("samplerate", [22050, 44100, 48000])
+def test_swapped_parameter_exception(tmp_path: pathlib.Path, extension: str, samplerate):
+ filename = str(tmp_path / f"test{extension}")
+ with pytest.raises(ValueError) as e:
+ pedalboard.io.WriteableAudioFile(filename, samplerate=1, num_channels=samplerate)
+ assert "reversing" in str(
+ e
+ ), "Expected exception to include details about reversing parameters."
+
+
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.uint64])
def test_fail_to_write_unsigned(tmp_path: pathlib.Path, dtype):
filename = str(tmp_path / "test.wav")