imetting/backend/app/utils/audio_parser.py

60 lines
1.4 KiB
Python
Raw Normal View History

"""
音频文件解析工具
用于解析音频文件的元数据信息如时长采样率编码格式等
"""
2026-04-09 09:51:34 +00:00
import json
import shutil
import subprocess
def get_audio_duration(file_path: str) -> int:
"""
获取音频文件时长
2026-04-09 09:51:34 +00:00
使用 ffprobe 读取音频时长
Args:
file_path: 音频文件的完整路径
Returns:
音频时长如果解析失败返回0
支持格式
- MP3 (.mp3)
- M4A (.m4a)
- MP4 (.mp4)
- WAV (.wav)
- OGG (.ogg)
- FLAC (.flac)
2026-04-09 09:51:34 +00:00
- 以及 ffprobe 支持的其他音频格式
"""
2026-04-09 09:51:34 +00:00
ffprobe_path = shutil.which("ffprobe")
if not ffprobe_path:
return 0
try:
2026-04-09 09:51:34 +00:00
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:
2026-04-09 09:51:34 +00:00
print(f"ffprobe 获取音频时长失败 ({file_path}): {e}")
return 0