Skip to content

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

Add tests to ensure audio fixtures are read properly.

Peter Sobot2736566748af
diff --git a/pedalboard/io/AudioFile.h b/pedalboard/io/AudioFile.h
index f70c3de..9d05e31 100644
--- a/pedalboard/io/AudioFile.h
+++ b/pedalboard/io/AudioFile.h
@@ -53,17 +53,22 @@ public:
// This is slower but more thorough:
reader.reset(formatManager.createReaderFor(file.createInputStream()));
- // Known bug: the juce::MP3Reader class will parse formats that are not MP3
- // and pretend like they are, producing garbage output. For now, if we parse MP3
- // from an input stream that's not explicitly got ".mp3" on the end, ignore it.
+ // Known bug: the juce::MP3Reader class will parse formats that are not
+ // MP3 and pretend like they are, producing garbage output. For now, if we
+ // parse MP3 from an input stream that's not explicitly got ".mp3" on the
+ // end, ignore it.
if (reader->getFormatName() == "MP3 file") {
- reader.reset();
+ throw std::domain_error(
+ "Failed to open audio file: file \"" + filename +
+ "\" does not seem to be of a known or supported format. (If trying "
+ "to open an MP3 file, ensure the filename ends with '.mp3'.)");
}
}
if (!reader)
- throw std::domain_error("Unable to open audio file for reading: " +
- filename);
+ throw std::domain_error(
+ "Failed to open audio file: file \"" + filename +
+ "\" does not seem to be of a known or supported format.");
}
double getSampleRate() const {
@@ -78,6 +83,12 @@ public:
return reader->lengthInSamples;
}
+ double getDuration() const {
+ if (!reader)
+ throw std::runtime_error("I/O operation on a closed file.");
+ return reader->lengthInSamples / reader->sampleRate;
+ }
+
long getNumChannels() const {
if (!reader)
throw std::runtime_error("I/O operation on a closed file.");
@@ -403,7 +414,7 @@ public:
break;
}
case ChannelLayout::NotInterleaved: {
- // We can just pass all the data to writeFromFloatArrays:
+ // We can just pass all the data to write:
const SampleType **channelPointers =
(const SampleType **)alloca(numChannels * sizeof(SampleType *));
for (int c = 0; c < numChannels; c++) {
@@ -467,7 +478,7 @@ public:
std::is_integral<TargetType>::value,
"Can't convert int to float");
} else {
- // Converting float to float:
+ // Converting double to float:
targetTypeBuffers[c][i] = channels[c][startSample + i];
}
}
@@ -496,15 +507,14 @@ public:
return writeConvertingTo<int>(channels, numChannels, numSamples);
}
} else if constexpr (std::is_same<SampleType, float>::value) {
- if (writer->isFloatingPoint()) {
+ if (writer->isFloatingPoint()) {
// Just pass the floating point data into the writer as if it were
// integer data. If the writer requires floating-point input data, this
// works (and is documented!)
return writer->write((const int **)channels, numSamples);
} else {
// Convert floating-point to fixed point, but let JUCE do that for us:
- return writer->writeFromFloatArrays(channels, numChannels,
- numSamples);
+ return writer->writeFromFloatArrays(channels, numChannels, numSamples);
}
} else {
// We must have double-format data:
@@ -678,6 +688,9 @@ inline void init_audiofile(py::module &m) {
.def_property_readonly("frames", &ReadableAudioFile::getLengthInSamples,
"Fetch the total number of frames (samples per "
"channel) in the file.")
+ .def_property_readonly(
+ "duration", &ReadableAudioFile::getDuration,
+ "Fetch the duration of this file (frames divided by sample rate).")
.def_property_readonly(
"file_dtype", &ReadableAudioFile::getFileDatatype,
"Fetch the data type stored natively by the file. Note that read() "
diff --git a/tests/audio/correct/mono_sine_at_44100Hz.mp2 b/tests/audio/correct/mono_sine_at_44100Hz.mp2
deleted file mode 100644
index 175e6d3..0000000
Binary files a/tests/audio/correct/mono_sine_at_44100Hz.mp2 and /dev/null differ
diff --git a/tests/audio/correct/mono_sine_at_48000Hz.mp2 b/tests/audio/correct/mono_sine_at_48000Hz.mp2
deleted file mode 100644
index e790270..0000000
Binary files a/tests/audio/correct/mono_sine_at_48000Hz.mp2 and /dev/null differ
diff --git a/tests/test_io.py b/tests/test_io.py
index b46c5b7..5f9d03a 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -51,6 +51,23 @@ UNSUPPORTED_FILENAMES = [
]
+def get_tolerance_for_format_and_bit_depth(extension: str, input_format, file_dtype: str) -> float:
+ if not extension.startswith("."):
+ extension = "." + extension
+ if extension in {".wav", ".aiff", ".aifc", ".flac"}:
+ file_bit_depth = int(file_dtype.replace("float", "").replace("int", ""))
+ if np.issubdtype(input_format, np.signedinteger):
+ input_bit_depth = np.dtype(input_format).itemsize * 8
+ return 4 / (2 ** min(file_bit_depth, input_bit_depth))
+ return 4 / (2**file_bit_depth)
+
+ # These formats offset the waveform substantially, and these tests don't do any realignment.
+ if extension in {".m4a", ".ac3", ".adts", ".mp4", ".mp2"}:
+ return 3.0
+
+ return 0.12
+
+
def test_read_constructor_dispatch():
filename, _samplerate = FILENAMES_AND_SAMPLERATES[0]
@@ -153,6 +170,16 @@ def test_basic_read(audio_filename: str, samplerate: float):
assert f"frames={af.frames}" in repr(af)
assert f"file_dtype={af.file_dtype}" in repr(af)
+ af.seek(0)
+ actual = af.read(af.frames)
+ expected = generate_sine_at(af.samplerate, num_channels=af.channels, num_seconds=af.duration)
+ # Crop the ends of the file, as lossy formats sometimes don't encode the whole file:
+ actual = actual[:, : len(expected)]
+ tolerance = get_tolerance_for_format_and_bit_depth(
+ audio_filename.split(".")[-1], np.int16, af.file_dtype
+ )
+ np.testing.assert_allclose(np.squeeze(expected), np.squeeze(actual), atol=tolerance)
+
af.close()
with pytest.raises(RuntimeError):
@@ -281,16 +308,7 @@ def test_basic_write(
with pedalboard.io.ReadableAudioFile(filename) as af:
assert af.samplerate == samplerate
assert af.channels == num_channels
-
- if extension == ".ogg":
- tolerance = 0.12
- else:
- file_bit_depth = int(af.file_dtype.replace("float", "").replace("int", ""))
- tolerance = 4 / (2 ** file_bit_depth)
- if np.issubdtype(input_format, np.signedinteger):
- input_bit_depth = np.dtype(input_format).itemsize * 8
- tolerance = 4 / (2 ** min(file_bit_depth, input_bit_depth))
-
+ tolerance = get_tolerance_for_format_and_bit_depth(extension, input_format, af.file_dtype)
as_written = af.read(num_samples)
np.testing.assert_allclose(original_audio, np.squeeze(as_written), atol=tolerance)