49 lines
1.4 KiB
Python
49 lines
1.4 KiB
Python
import subprocess
|
||
from pathlib import Path
|
||
|
||
|
||
def convert_to_h264(input_root: Path, vid_full_name: str, output_root: Path) -> str:
|
||
"""
|
||
将视频文件转码为 H.264 编码格式
|
||
|
||
Args:
|
||
input_path: 输入视频文件路径(相对或绝对路径)
|
||
output_path: 输出视频文件路径(可选,默认为输入文件同名_h264.mp4)
|
||
|
||
Returns:
|
||
转码后的视频文件路径
|
||
|
||
Raises:
|
||
FileNotFoundError: 输入文件不存在
|
||
subprocess.CalledProcessError: FFmpeg 转码失败
|
||
"""
|
||
input_path_all = Path(input_root,vid_full_name).resolve()
|
||
output_vid_full_name = f"{Path(vid_full_name).stem}_h264.mp4"
|
||
output_path_all = Path(output_root, output_vid_full_name).resolve()
|
||
|
||
if not input_path_all.exists():
|
||
raise FileNotFoundError(f"输入文件不存在:{input_path_all}")
|
||
|
||
print(f"开始转码:{input_path_all}")
|
||
|
||
cmd = [
|
||
"ffmpeg",
|
||
"-i", str(input_path_all),
|
||
"-c:v", "h264_nvenc", # NVIDIA 硬件编码
|
||
"-c:a", "aac",
|
||
"-b:a", "128k",
|
||
"-y",
|
||
str(output_path_all)
|
||
]
|
||
|
||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||
|
||
if result.returncode != 0:
|
||
raise subprocess.CalledProcessError(
|
||
result.returncode,
|
||
cmd,
|
||
result.stdout,
|
||
result.stderr
|
||
)
|
||
print(f"转码完成:{output_path_all}")
|
||
return str(output_path_all) |