Skip to content

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

Allow accessing AudioFile metadata after closing. (#313)

Peter Sobot98efdb986956
diff --git a/pedalboard/io/ReadableAudioFile.h b/pedalboard/io/ReadableAudioFile.h
index 5bc864d..574c342 100644
--- a/pedalboard/io/ReadableAudioFile.h
+++ b/pedalboard/io/ReadableAudioFile.h
@@ -84,6 +84,8 @@ public:
throw std::domain_error("Failed to open audio file: file \"" + filename +
"\" does not seem to contain audio data in a "
"known or supported format.");
+
+ cacheMetadata();
}
ReadableAudioFile(std::unique_ptr<PythonInputStream> inputStream) {
@@ -169,51 +171,72 @@ public:
}
PythonException::raise();
+ cacheMetadata();
}
- std::variant<double, long> getSampleRate() const {
- const juce::ScopedReadLock scopedLock(objectLock);
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
+ void cacheMetadata() {
+ sampleRate = reader->sampleRate;
+ numChannels = reader->numChannels;
+ numFrames = reader->lengthInSamples;
+
+ if (reader->usesFloatingPointData) {
+ switch (reader->bitsPerSample) {
+ case 16: // OGG returns 16-bit int data, but internally stores floats
+ case 32:
+ fileDatatype = "float32";
+ break;
+ case 64:
+ fileDatatype = "float64";
+ break;
+ default:
+ fileDatatype = "unknown";
+ break;
+ }
+ } else {
+ switch (reader->bitsPerSample) {
+ case 8:
+ fileDatatype = "int8";
+ break;
+ case 16:
+ fileDatatype = "int16";
+ break;
+ case 24:
+ fileDatatype = "int24";
+ break;
+ case 32:
+ fileDatatype = "int32";
+ break;
+ case 64:
+ fileDatatype = "int64";
+ break;
+ default:
+ fileDatatype = "unknown";
+ break;
+ }
+ }
+ }
+ std::variant<double, long> getSampleRate() const {
double integerPart;
- double fractionalPart = std::modf(reader->sampleRate, &integerPart);
+ double fractionalPart = std::modf(sampleRate, &integerPart);
if (fractionalPart > 0) {
- return reader->sampleRate;
+ return sampleRate;
} else {
- return (long)(reader->sampleRate);
+ return (long)(sampleRate);
}
}
- double getSampleRateAsDouble() const {
- const juce::ScopedReadLock scopedLock(objectLock);
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
-
- return reader->sampleRate;
- }
+ double getSampleRateAsDouble() const { return sampleRate; }
long long getLengthInSamples() const {
const juce::ScopedReadLock scopedLock(objectLock);
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
- return reader->lengthInSamples + (lengthCorrection ? *lengthCorrection : 0);
+ return numFrames + (lengthCorrection ? *lengthCorrection : 0);
}
- double getDuration() const {
- const juce::ScopedReadLock scopedLock(objectLock);
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
- return getLengthInSamples() / reader->sampleRate;
- }
+ double getDuration() const { return numFrames / getSampleRateAsDouble(); }
- long getNumChannels() const {
- const juce::ScopedReadLock scopedLock(objectLock);
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
- return reader->numChannels;
- }
+ long getNumChannels() const { return numChannels; }
std::string getFileFormat() const {
const juce::ScopedReadLock scopedLock(objectLock);
@@ -223,37 +246,7 @@ public:
return reader->getFormatName().toStdString();
}
- std::string getFileDatatype() const {
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
-
- if (reader->usesFloatingPointData) {
- switch (reader->bitsPerSample) {
- case 16: // OGG returns 16-bit int data, but internally stores floats
- case 32:
- return "float32";
- case 64:
- return "float64";
- default:
- return "unknown";
- }
- } else {
- switch (reader->bitsPerSample) {
- case 8:
- return "int8";
- case 16:
- return "int16";
- case 24:
- return "int24";
- case 32:
- return "int32";
- case 64:
- return "int64";
- default:
- return "unknown";
- }
- }
- }
+ std::string getFileDatatype() const { return fileDatatype; }
py::array_t<float, py::array::c_style>
read(std::variant<double, long long> numSamplesVariant) {
@@ -603,8 +596,6 @@ public:
long long tell() const {
py::gil_scoped_release release;
const juce::ScopedReadLock scopedLock(objectLock);
- if (!reader)
- throw std::runtime_error("I/O operation on a closed file.");
return currentPosition;
}
@@ -733,6 +724,11 @@ private:
std::unique_ptr<juce::AudioFormatReader> reader;
juce::ReadWriteLock objectLock;
+ double sampleRate;
+ long numChannels;
+ long numFrames;
+ std::string fileDatatype;
+
long long currentPosition = 0;
// Certain files (notably CBR MP3 files) can report the wrong number of
@@ -912,14 +908,15 @@ in which this may occur.)
ss << " file_like=" << stream->getRepresentation();
}
+ ss << " samplerate=" << file.getSampleRateAsDouble();
+ ss << " num_channels=" << file.getNumChannels();
+ ss << " frames=" << file.getLengthInSamples();
+ ss << " file_dtype=" << file.getFileDatatype();
+
if (file.isClosed()) {
ss << " closed";
- } else {
- ss << " samplerate=" << file.getSampleRateAsDouble();
- ss << " num_channels=" << file.getNumChannels();
- ss << " frames=" << file.getLengthInSamples();
- ss << " file_dtype=" << file.getFileDatatype();
}
+
ss << " at " << &file;
ss << ">";
return ss.str();
diff --git a/tests/test_io.py b/tests/test_io.py
index 47ce1af..0caf98c 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -200,8 +200,12 @@ def test_basic_read(audio_filename: str, samplerate: float):
af.close()
- with pytest.raises(RuntimeError):
- af.num_channels
+ # Should be able to read properties of the file even after it's been closed:
+ assert af.num_channels == 1
+ assert af.samplerate == samplerate
+ assert f"samplerate={int(af.samplerate)}" in repr(af)
+ assert f"num_channels={af.num_channels}" in repr(af)
+ assert "closed" in repr(af)
with pytest.raises(RuntimeError):
af.read(1)
@@ -218,6 +222,7 @@ def test_read_raw(audio_filename: str, samplerate: float):
@pytest.mark.parametrize("audio_filename,samplerate", FILENAMES_AND_SAMPLERATES)
def test_use_reader_as_context_manager(audio_filename: str, samplerate: float):
+ num_frames_when_open = None
with pedalboard.io.AudioFile(audio_filename) as af:
assert af.samplerate == samplerate
assert af.num_channels == 1
@@ -225,6 +230,7 @@ def test_use_reader_as_context_manager(audio_filename: str, samplerate: float):
assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
else:
assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
+ num_frames_when_open = af.frames
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
@@ -245,10 +251,17 @@ def test_use_reader_as_context_manager(audio_filename: str, samplerate: float):
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
+ assert "closed" not in repr(af)
- with pytest.raises(RuntimeError):
- af.num_channels
+ # Should be able to read properties of the file even after it's been closed:
+ assert af.num_channels == 1
+ assert af.samplerate == samplerate
+ assert af.frames == num_frames_when_open
+ assert f"samplerate={int(af.samplerate)}" in repr(af)
+ assert f"num_channels={af.num_channels}" in repr(af)
+ assert "closed" in repr(af)
+ # ... but reading from a closed file is still an error:
with pytest.raises(RuntimeError):
af.read(1)
@@ -279,6 +292,7 @@ def test_read_from_seekable_stream(audio_filename: str, samplerate: float):
af = pedalboard.io.AudioFile(stream)
+ num_frames_when_open = None
with af:
assert af.samplerate == samplerate
assert af.num_channels == 1
@@ -286,6 +300,7 @@ def test_read_from_seekable_stream(audio_filename: str, samplerate: float):
assert af.frames == int(samplerate * EXPECTED_DURATION_SECONDS)
else:
assert af.frames >= int(samplerate * EXPECTED_DURATION_SECONDS)
+ num_frames_when_open = af.frames
samples = af.read(int(samplerate * EXPECTED_DURATION_SECONDS))
assert samples.shape == (1, int(samplerate * EXPECTED_DURATION_SECONDS))
@@ -307,9 +322,17 @@ def test_read_from_seekable_stream(audio_filename: str, samplerate: float):
assert f"samplerate={int(af.samplerate)}" in repr(af)
assert f"num_channels={af.num_channels}" in repr(af)
assert repr(stream) in repr(af)
+ assert "closed" not in repr(af)
- with pytest.raises(RuntimeError):
- af.num_channels
+ # Should be able to read properties of the file even after it's been closed:
+ assert af.num_channels == 1
+ assert af.samplerate == samplerate
+ assert af.frames == num_frames_when_open
+ assert f"samplerate={int(af.samplerate)}" in repr(af)
+ assert f"num_channels={af.num_channels}" in repr(af)
+ assert "closed" in repr(af)
+
+ # ... but reading from a closed file is still an error:
with pytest.raises(RuntimeError):
af.read(1)