python check audio file type, MP3 or FLAC

梦想与她 提交于 2021-01-19 09:07:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!