2026-01-19 11:03:08 +00:00
|
|
|
|
"""
|
|
|
|
|
|
音频文件解析工具
|
|
|
|
|
|
|
|
|
|
|
|
用于解析音频文件的元数据信息,如时长、采样率、编码格式等
|
|
|
|
|
|
"""
|
2026-04-09 09:51:34 +00:00
|
|
|
|
import json
|
|
|
|
|
|
import shutil
|
|
|
|
|
|
import subprocess
|
2026-01-19 11:03:08 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_audio_duration(file_path: str) -> int:
|
|
|
|
|
|
"""
|
|
|
|
|
|
获取音频文件时长(秒)
|
|
|
|
|
|
|
2026-04-09 09:51:34 +00:00
|
|
|
|
使用 ffprobe 读取音频时长
|
2026-01-19 11:03:08 +00:00
|
|
|
|
|
|
|
|
|
|
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-01-19 11:03:08 +00:00
|
|
|
|
"""
|
2026-04-09 09:51:34 +00:00
|
|
|
|
ffprobe_path = shutil.which("ffprobe")
|
|
|
|
|
|
if not ffprobe_path:
|
|
|
|
|
|
return 0
|
|
|
|
|
|
|
2026-01-19 11:03:08 +00:00
|
|
|
|
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))
|
2026-01-19 11:03:08 +00:00
|
|
|
|
except Exception as e:
|
2026-04-09 09:51:34 +00:00
|
|
|
|
print(f"ffprobe 获取音频时长失败 ({file_path}): {e}")
|
2026-01-19 11:03:08 +00:00
|
|
|
|
|
|
|
|
|
|
return 0
|