imetting/backend/app/utils/audio_parser.py

39 lines
856 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
音频文件解析工具
用于解析音频文件的元数据信息,如时长、采样率、编码格式等
"""
from tinytag import TinyTag
def get_audio_duration(file_path: str) -> int:
"""
获取音频文件时长(秒)
使用TinyTag读取音频文件时长
Args:
file_path: 音频文件的完整路径
Returns:
音频时长如果解析失败返回0
支持格式:
- MP3 (.mp3)
- M4A (.m4a)
- MP4 (.mp4)
- WAV (.wav)
- OGG (.ogg)
- FLAC (.flac)
- 以及TinyTag支持的其他音频格式
"""
try:
tag = TinyTag.get(file_path)
if tag.duration and tag.duration > 0:
return int(tag.duration)
except Exception as e:
print(f"获取音频时长失败 ({file_path}): {e}")
return 0