python 检查音频文件类型,MP3 或 FLAC

twi*_*igg 3 python audio mp3 flac

我想检查音频文件是 MP3 还是 FLAC,检查只需进行基本检查,但我想要的不仅仅是检查文件扩展名

os.path.splitext
Run Code Online (Sandbox Code Playgroud)

工作正常,但如果文件没有写入扩展名或有人传递了带有假扩展名的文件,则效果不佳

我已经尝试过,但它只返回 None

sndhdr.what(file)
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用魔法,但它返回“application/octet-stream”,这没有多大用处。

magic.from_file(file, mime=True)
Run Code Online (Sandbox Code Playgroud)

我读过 Mutagen 可能对此很有帮助,但到目前为止未能找到任何将音频编码输出为 MP3 或 FLAC 的函数

Str*_*ker 6

要查找文件格式(包括音频、视频、txt 等),您可以使用 fleeppython 库来检查音频文件格式:

首先您需要安装该库:

pip install fleep
Run Code Online (Sandbox Code Playgroud)

这是一个测试代码:

import fleep

with open("vida.flac", "rb") as file:
    info = fleep.get(file.read(128))

print(info.type)
print(info.extension)
print(info.mime) 
Run Code Online (Sandbox Code Playgroud)

结果如下:

['audio']
['flac']
['audio/flac']
Run Code Online (Sandbox Code Playgroud)

即使文件没有扩展名或者有人传递了带有假扩展名的文件,它也会检测并返回。

这里我已将 vida.wav 文件复制到 dar.txt 并删除了扩展名

import fleep

with open("dar", "rb") as file:
    info = fleep.get(file.read(128))

print(info.type)
print(info.extension) 
print(info.mime) 
Run Code Online (Sandbox Code Playgroud)

结果还是一样。

['audio']
['flac']
['audio/flac']
Run Code Online (Sandbox Code Playgroud)

感谢该库的作者 https://github.com/floyernick/fleep-py