使用sndhdr库的what()函数判断音频文件格式的实例演示
发布时间:2023-12-16 11:23:41
sndhdr是Python标准库中的一个模块,提供了一些函数来判断音频文件的格式。其中,what()函数可以用来判断音频文件的格式。
下面是一个实例演示,如何使用sndhdr库的what()函数来判断音频文件的格式:
import sndhdr
def get_audio_format(file_path):
try:
# 使用what()函数来判断音频文件的格式
result = sndhdr.what(file_path)
if result is None:
return "Unknown format"
else:
return result.filetype
except FileNotFoundError:
return "File not found"
# 示例使用
file1 = "music.mp3"
file2 = "sound.wav"
file3 = "audio.flac"
file4 = "speech.aiff"
format1 = get_audio_format(file1)
format2 = get_audio_format(file2)
format3 = get_audio_format(file3)
format4 = get_audio_format(file4)
print(f"{file1}: {format1}")
print(f"{file2}: {format2}")
print(f"{file3}: {format3}")
print(f"{file4}: {format4}")
在上面的代码中,get_audio_format()函数接受一个音频文件的路径作为参数,然后使用sndhdr库的what()函数来判断文件的格式。如果文件格式无法识别,则返回"Unknown format";如果文件不存在,则返回"File not found";否则返回对应的格式。
最后,我们通过给定音频文件的路径,调用get_audio_format()函数并打印结果,来展示如何判断音频文件的格式。
