简体   繁体   English

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

[英]python check audio file type, MP3 or FLAC

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我想检查一个音频文件是否是 MP3 或 FLAC 检查只需要是基本的,但我想不仅仅是检查文件扩展名

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我试过了,但它只返回 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我读过 Mutagen 可能对此有好处,但到目前为止未能找到任何将音频编码输出为 MP3 或 FLAC 的函数

To find the File format including audio, video, txt and more, you can use fleep python library to check the audio file format:要查找包括音频、视频、txt 等在内的文件格式,您可以使用fleep python 库来检查音频文件格式:

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这里我已经将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) 

The result is still the same.结果还是一样。

['audio']
['flac']
['audio/flac']

Credit to the author of the library https://github.com/floyernick/fleep-py感谢图书馆作者https://github.com/floyernick/fleep-py

This might help you getting started这可能会帮助您入门

21.9. 21.9. sndhdr — Determine type of sound file sndhdr — 确定声音文件的类型

https://docs.python.org/2/library/sndhdr.html https://docs.python.org/2/library/sndhdr.html

您可以阅读 mp3 和 flac 的文件规范,然后可以实现一个检查器,将 mp3 读取和解析为二进制文件。具有类似目标的可修改示例是here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM