Skip to content

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

Fix AudioFile behaviour when overwriting existing files.

Peter Sobote1c7d6450b35
diff --git a/pedalboard/io/WriteableAudioFile.h b/pedalboard/io/WriteableAudioFile.h
index 06d0087..2b6ee39 100644
--- a/pedalboard/io/WriteableAudioFile.h
+++ b/pedalboard/io/WriteableAudioFile.h
@@ -158,6 +158,12 @@ public:
return juce::FileOutputStream::write(bytes, len);
}
+ virtual juce::int64 getPosition() override {
+ if (!hasWrittenToFile)
+ return 0;
+ return juce::FileOutputStream::getPosition();
+ }
+
virtual bool writeRepeatedByte(juce::uint8 byte,
size_t numTimesToRepeat) override {
if (!hasWrittenToFile) {
@@ -261,7 +267,7 @@ public:
extension = file.getFileExtension().toStdString();
outputStream = AutoDeleteFileOutputStream::createOutputStream(file);
- if (!static_cast<juce::FileOutputStream *>(outputStream.get())
+ if (!static_cast<AutoDeleteFileOutputStream *>(outputStream.get())
->openedOk()) {
throw std::domain_error("Unable to open audio file for writing: " +
filename);
diff --git a/tests/test_io.py b/tests/test_io.py
index c8a97e6..889bd2d 100644
--- a/tests/test_io.py
+++ b/tests/test_io.py
@@ -661,6 +661,44 @@ def test_write_to_seekable_stream(
np.testing.assert_allclose(original_audio, np.squeeze(as_written), atol=tolerance)
[email protected]("extension", pedalboard.io.get_supported_write_formats())
[email protected]("samplerate", [32000, 44100, 48000])
[email protected]("num_channels", [1, 2])
+def test_write_twice_overwrites(
+ tmp_path: pathlib.Path, extension: str, samplerate: float, num_channels: int
+):
+ filename = str(tmp_path / f"test{extension}")
+ original_audio = np.zeros((num_channels, samplerate))
+
+ with pedalboard.io.AudioFile(
+ filename, "w", samplerate=samplerate, num_channels=num_channels
+ ) as af:
+ af.write(original_audio)
+
+ assert os.path.exists(filename)
+ assert os.path.getsize(filename) > 0
+
+ with pedalboard.io.AudioFile(filename) as af:
+ assert af.samplerate == samplerate
+ assert af.num_channels == num_channels
+ assert af.frames > 0
+ first_read_result = af.read(af.frames)
+
+ # Write again:
+ with pedalboard.io.AudioFile(
+ filename, "w", samplerate=samplerate, num_channels=num_channels
+ ) as af:
+ af.write(original_audio)
+
+ with pedalboard.io.AudioFile(filename) as af:
+ assert af.samplerate == samplerate
+ assert af.num_channels == num_channels
+ assert af.frames > 0
+ second_read_result = af.read(af.frames)
+
+ np.testing.assert_allclose(second_read_result, first_read_result)
+
+
@pytest.mark.parametrize("extension", pedalboard.io.get_supported_write_formats())
@pytest.mark.parametrize("samplerate", [1234.5, 23.0000000001])
def test_fractional_sample_rates(tmp_path: pathlib.Path, extension: str, samplerate):