python-soundfile icon indicating copy to clipboard operation
python-soundfile copied to clipboard

Opening file in write mode removes existing metadata

Open sammlapp opened this issue 3 years ago • 2 comments

It seems that simply opening a SoundFile (version 0.10.3.post1, which is what I get when I run pip install soundfile) in write mode removes existing metadata in the wav file. For instance, if audio.wav has a string in the comment field of the metadata "this is a comment", after opening the file and closing it like so:

with soundfile.SoundFile(audio.wav,samplerate=32000,channels=1,mode='w') as s:
    pass

the comment field is now null. Perhaps this is the expected behavior, but from my perspective, it is a major disadvantage of using SoundFile to read/write audio files or tags. For instance, I thought I could update one piece of the metadata while leaving the rest intact like this:

with soundfile.SoundFile(audio.wav,samplerate=32000,channels=1,mode='w') as s:
    s.__setattr__('artist','me')

however, this results in the elimination of data in the other fields.

sammlapp avatar Nov 22 '21 17:11 sammlapp

This is indeed the expected behavior, and it is modeled after the built-in Python function open(). It is documented in detail in the python-soundfile docs.

The mode 'w' truncates the file, so it shouldn't be surprising that the metadata is destroyed as well.

Please note that the complete audio content of your file is deleted, not only the metadata!

In your examples you can see that you have to specify a samplerate and channels, which only makes sense if the existing content is removed.

If you want to update the file without truncating (and without removing information about samplerate, channels and metadata), you should use the 'r+' mode, as you would for normal Python file objects. In this case, you don't have to specify samplerate and channels, because this information is taken from the existing file.

mgeier avatar Nov 22 '21 21:11 mgeier

I'm returning to this now, and this helped me. Thank you.

sammlapp avatar Sep 20 '22 13:09 sammlapp