问题
I want to check if a audio file to see if its MP3 or FLAC the checks only have to be basic but I want to go beyond simply checking the file extensions
os.path.splitext
Works okay but no good if the file doesn't have an extensions written in or someone passes a file with a fake extension
I've tried but it just returns None
sndhdr.what(file)
I've also tried using magic but it returns 'application/octet-stream' which isn't much use.
magic.from_file(file, mime=True)
I've read Mutagen could be good for this but so far failed to find any function that outputs the audio encoding as MP3 or FLAC
回答1:
To find the File format including audio, video, txt and more, you can use
fleep
python library to check the audio file format:
First you need to install the library:
pip install fleep
Here is a test code:
import fleep
with open("vida.flac", "rb") as file:
info = fleep.get(file.read(128))
print(info.type)
print(info.extension)
print(info.mime)
Here is the results:
['audio']
['flac']
['audio/flac']
Even if the file doesn't have an extension or someone passes a file with a fake extension, it will detect and return.
Here I have copied the vida.wav file to dar.txt and also removed the extension
import fleep
with open("dar", "rb") as file:
info = fleep.get(file.read(128))
print(info.type)
print(info.extension)
print(info.mime)
The result is still the same.
['audio']
['flac']
['audio/flac']
Credit to the author of the library https://github.com/floyernick/fleep-py
回答2:
This might help you getting started
21.9. sndhdr — Determine type of sound file
https://docs.python.org/2/library/sndhdr.html
回答3:
You can read file specifications of mp3 and flac and then can implement a checker that reads and parses mp3 as a binary file.A modifiable example with a similar goal is here
来源:https://stackoverflow.com/questions/30322439/python-check-audio-file-type-mp3-or-flac