bastibe / python-soundfile

SoundFile is an audio library based on libsndfile, CFFI, and NumPy
BSD 3-Clause "New" or "Revised" License
717 stars 111 forks source link

Cannot read mp3 with file-like object #439

Open BakerBunker opened 4 months ago

BakerBunker commented 4 months ago

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

bastibe commented 4 months ago

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

BakerBunker commented 4 months ago

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

bastibe commented 4 months ago

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

BakerBunker commented 4 months ago

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.

bastibe commented 4 months ago

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

BakerBunker commented 4 months ago

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
bastibe commented 4 months ago

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