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

Cannot read mp3 with file-like object

Open BakerBunker opened this issue 1 year ago • 7 comments

I tried to read a mp3 with file handle, but soundfile failed to read.

import soundfile as sf

ret = sf.read("052316.mp3")
print(ret)

try:
    sf.read(open("052316.mp3", "rb"))
except Exception as e:
    print(e)

it shows

(array([[0., 0.],
       [0., 0.],
       [0., 0.],
       ...,
       [0., 0.],
       [0., 0.],
       [0., 0.]]), 44100)
Error opening <_io.BufferedReader name='052316.mp3'>: Format not recognised.

and here is the file 052316.mp3.zip

BakerBunker avatar Jul 12 '24 08:07 BakerBunker

Since no file name is available with open, you need to provide a format and subtype manually.

bastibe avatar Jul 15 '24 11:07 bastibe

Is it possible to try to get the file name with name property?

https://github.com/python/cpython/blob/8303d32ff55945c5b38eeeaf1b1811dbcf8aa9be/Lib/typing.py#L3472-L3475

BakerBunker avatar Jul 15 '24 11:07 BakerBunker

The code is here: https://github.com/bastibe/python-soundfile/blob/master/soundfile.py#L650

bastibe avatar Jul 15 '24 14:07 bastibe

According to PEP519, the __fspath__ method is only for the path-like object, for file-like objects created by open and remote file-like objects created by smart_open, the filename should accessed by name property.

BakerBunker avatar Jul 16 '24 05:07 BakerBunker

It should be reading the format from the name property: https://github.com/bastibe/python-soundfile/blob/master/soundfile.py#L1466

bastibe avatar Jul 16 '24 11:07 bastibe

It's strange, I get an error when I open the above file with sf.read(open("052316.mp3",'rb')), but not when I open this one, is it because the metadata is different? 111097.mp3.zip

file 052316.mp3
> Audio file with ID3 version 2.4.0
file 111097.mp3
> Audio file with ID3 version 2.4.0, contains: MPEG ADTS, layer III, v1, 320 kbps, 44.1 kHz, Stereo

BakerBunker avatar Jul 16 '24 11:07 BakerBunker

Perhaps the file is broken in some way? Libsndfile is a bit more stringent in its MP3 implementation than some other libs.

bastibe avatar Jul 17 '24 05:07 bastibe