imetting/backend/app/utils/audio_parser.py

60 lines
1.4 KiB
Python
Raw 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.

"""
音频文件解析工具
用于解析音频文件的元数据信息,如时长、采样率、编码格式等
"""
import json
import shutil
import subprocess
def get_audio_duration(file_path: str) -> int:
"""
获取音频文件时长(秒)
使用 ffprobe 读取音频时长
Args:
file_path: 音频文件的完整路径
Returns:
音频时长如果解析失败返回0
支持格式:
- MP3 (.mp3)
- M4A (.m4a)
- MP4 (.mp4)
- WAV (.wav)
- OGG (.ogg)
- FLAC (.flac)
- 以及 ffprobe 支持的其他音频格式
"""
ffprobe_path = shutil.which("ffprobe")
if not ffprobe_path:
return 0
try:
completed = subprocess.run(
[
ffprobe_path,
"-v",
"error",
"-print_format",
"json",
"-show_format",
str(file_path),
],
check=False,
capture_output=True,
text=True,
)
if completed.returncode == 0 and completed.stdout:
payload = json.loads(completed.stdout)
duration_value = (payload.get("format") or {}).get("duration")
if duration_value:
return int(float(duration_value))
except Exception as e:
print(f"ffprobe 获取音频时长失败 ({file_path}): {e}")
return 0