Files
COMP90044_a1/1.py
2025-04-14 17:15:38 +10:00

49 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import subprocess
import tempfile
import shutil
# 根目录
input_dir = r"D:\DESKTOP\2025\44\a1\dataset" # 替换为你的视频根目录
video_exts = {".avi", ".mov", ".mkv", ".flv", ".webm", ".wmv", ".mp4",".m4s"}
def convert_and_replace(filepath):
ext = os.path.splitext(filepath)[1].lower()
if ext not in video_exts:
return
print(f"处理文件: {filepath}")
# 创建临时输出文件
temp_fd, temp_path = tempfile.mkstemp(suffix=".mp4")
os.close(temp_fd) # 不使用 open 的文件描述符
# ffmpeg 转换命令保留前30秒360p输出mp4
cmd = [
"ffmpeg",
"-y",
"-i", filepath,
"-t", "30",
"-vf", "scale=-2:480",
"-c:v", "libx264", # 改为 libx265 可使用 H.265
"-preset", "slow",
"-crf", "18",
"-c:a", "aac",
"-b:a", "64k",
temp_path
]
try:
subprocess.run(cmd, check=True)
shutil.move(temp_path, filepath)
print(f"已替换: {filepath}")
except subprocess.CalledProcessError as e:
print(f"失败: {filepath}\n{e}")
if os.path.exists(temp_path):
os.remove(temp_path)
# 递归遍历处理
for root, _, files in os.walk(input_dir):
for name in files:
file_path = os.path.join(root, name)
convert_and_replace(file_path)