1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
| import os import subprocess import time import tkinter as tk from tkinter import filedialog, messagebox, ttk
class UltimateMKVToolNixClipper: def __init__(self, root): self.root = root self.root.title("FFmpeg 裁剪 + MKVToolNix 黄金混流工具 (完美定制版)") self.root.geometry("620x500") self.root.resizable(False, False) self.video_path = tk.StringVar() self.audio_path = tk.StringVar() self.sub_path = tk.StringVar() self.out_dir = tk.StringVar() self.out_name = tk.StringVar(value="Defaultname") self.create_widgets()
def create_widgets(self): file_frame = tk.LabelFrame(self.root, text=" 1. 文件选择 ", padx=10, pady=10) file_frame.pack(fill="x", padx=15, pady=10)
tk.Label(file_frame, text="视频原片:").grid(row=0, column=0, sticky="e", pady=5) tk.Entry(file_frame, textvariable=self.video_path, width=52).grid(row=0, column=1, padx=5) tk.Button(file_frame, text="浏览...", command=self.select_video).grid(row=0, column=2) tk.Label(file_frame, text="音频原片:").grid(row=1, column=0, sticky="e", pady=5) self.audio_entry = tk.Entry(file_frame, textvariable=self.audio_path, width=52) self.audio_entry.grid(row=1, column=1, padx=5) tk.Button(file_frame, text="浏览...", command=self.select_audio).grid(row=1, column=2)
tk.Label(file_frame, text="字幕文件:").grid(row=2, column=0, sticky="e", pady=5) tk.Entry(file_frame, textvariable=self.sub_path, width=52).grid(row=2, column=1, padx=5) tk.Button(file_frame, text="浏览...", command=self.select_sub).grid(row=2, column=2)
time_frame = tk.LabelFrame(self.root, text=" 2. 裁剪时间轴 ", padx=10, pady=10) time_frame.pack(fill="x", padx=15, pady=5)
tk.Label(time_frame, text="开始时间 (-ss):").grid(row=0, column=0, padx=5) self.ent_ss = tk.Entry(time_frame, width=15, justify="center") self.ent_ss.insert(0, "00:00:00") self.ent_ss.grid(row=0, column=1, padx=5)
tk.Label(time_frame, text="结束时间 (-to):").grid(row=0, column=2, padx=25) self.ent_to = tk.Entry(time_frame, width=15, justify="center") self.ent_to.insert(0, "00:00:00") self.ent_to.grid(row=0, column=3, padx=5)
out_frame = tk.LabelFrame(self.root, text=" 3. 输出配置 ", padx=10, pady=10) out_frame.pack(fill="x", padx=15, pady=10)
tk.Label(out_frame, text="输出目录:").grid(row=0, column=0, sticky="e", pady=5) tk.Entry(out_frame, textvariable=self.out_dir, width=52).grid(row=0, column=1, padx=5) tk.Button(out_frame, text="更改...", command=self.select_out_dir).grid(row=0, column=2)
tk.Label(out_frame, text="输出名称:").grid(row=1, column=0, sticky="e", pady=5) tk.Entry(out_frame, textvariable=self.out_name, width=20).grid(row=1, column=1, sticky="w", padx=5)
tk.Label(out_frame, text="字幕模式:").grid(row=2, column=0, sticky="e", pady=5) self.combo_mode = ttk.Combobox(out_frame, values=["仅单独输出外挂字幕 (.ass)", "仅将字幕写入视频容器中 (.mkv)", "两个都要 (Both - 独立外挂+内置混合版)"], width=32, state="readonly") self.combo_mode.current(2) self.combo_mode.grid(row=2, column=1, sticky="w", padx=5)
tk.Button(self.root, text="🚀 开始全自动黄金组合剪辑 (MKVToolNix内核)", font=("微软雅黑", 12, "bold"), bg="#107C41", fg="white", command=self.run_clipper, pady=5).pack(fill="x", padx=15, pady=12)
def check_has_audio(self, video_file): """利用 ffprobe 自动探测视频是否包含音频流""" try: cmd = ['ffprobe', '-v', 'error', '-select_streams', 'a', '-show_entries', 'stream=index', '-of', 'csv=p=0', video_file] result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore') return len(result.stdout.strip()) > 0 except Exception: return True
def select_video(self): path = filedialog.askopenfilename(filetypes=[("视频文件", "*.mkv *.mp4"), ("所有文件", "*.*")]) if path: path = os.path.normpath(path) self.video_path.set(path) self.out_dir.set(os.path.dirname(path)) if self.check_has_audio(path): self.audio_path.set("【已检测到原视频自带音频轨道】(可在此另外浏览添加外挂音频)") else: self.audio_path.set("【未检测到原视频自带音频】(请在此浏览添加外挂音频)") base_without_ext = os.path.splitext(path)[0] possible_ass = base_without_ext + ".ass" if os.path.exists(possible_ass): self.sub_path.set(possible_ass)
def select_audio(self): path = filedialog.askopenfilename(filetypes=[("音频文件", "*.dts *.ac3 *.m4a *.mp3 *.wav *.aac"), ("所有文件", "*.*")]) if path: self.audio_path.set(os.path.normpath(path))
def select_sub(self): path = filedialog.askopenfilename(filetypes=[("字幕文件", "*.ass *.srt"), ("所有文件", "*.*")]) if path: self.sub_path.set(os.path.normpath(path))
def select_out_dir(self): path = filedialog.askdirectory() if path: self.out_dir.set(os.path.normpath(path))
def make_ass_top_display(self, ass_file_path): """强制改写 ASS 字幕脚本的样式区,令其在作为外挂次字幕时全部“屏幕居上”""" if not os.path.exists(ass_file_path): return try: with open(ass_file_path, 'r', encoding='utf-8', errors='ignore') as f: lines = f.readlines() new_lines = [] for line in lines: if line.startswith('Style:'): parts = line.split(',') if len(parts) > 6: pass new_lines.append(line) else: new_lines.append(line) fixed_lines = [] for line in new_lines: if line.startswith('Dialogue:'): pos = 0 comma_count = 0 for i, char in enumerate(line): if char == ',': comma_count += 1 if comma_count == 9: pos = i + 1 break if pos > 0: prefix = line[:pos] suffix = line[pos:] if not suffix.startswith(r'{\an8}'): line = prefix + r'{\an8}' + suffix fixed_lines.append(line) with open(ass_file_path, 'w', encoding='utf-8') as f: f.writelines(fixed_lines) except Exception as e: print(f"外挂字幕居上转换提示(不影响生成): {e}")
def find_mkvmerge(self): """智能寻找电脑中 MKVToolNix 的 mkvmerge 核心执行文件路径""" try: subprocess.run(['mkvmerge', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return 'mkvmerge' except FileNotFoundError: pass possible_dirs = [ r"C:\Program Files\MKVToolNix", r"C:\Program Files (x86)\MKVToolNix", r"D:\Program Files\MKVToolNix", r"E:\Program Files\MKVToolNix" ] for d in possible_dirs: exe_path = os.path.join(d, "mkvmerge.exe") if os.path.exists(exe_path): return exe_path return None
def run_clipper(self): v_in = self.video_path.get() a_in = self.audio_path.get() s_in = self.sub_path.get() ss = self.ent_ss.get().strip() to = self.ent_to.get().strip() o_dir = self.out_dir.get() o_name = self.out_name.get().strip() mode_idx = str(self.combo_mode.current() + 1)
if not v_in or not os.path.exists(v_in): messagebox.showerror("错误", "请选择有效的视频文件!") return if not s_in or not os.path.exists(s_in): messagebox.showerror("错误", "请选择有效的字幕文件!") return if not o_name: messagebox.showerror("错误", "请输入输出文件名!") return
mkvmerge_exe = self.find_mkvmerge() if mode_idx in ['2', '3'] and not mkvmerge_exe: messagebox.showerror("找不到 MKVToolNix", "未在系统或默认安装目录中找到 MKVToolNix,请确保已安装!") return
final_mkv = os.path.join(o_dir, f"{o_name}.mkv") final_ass = os.path.join(o_dir, f"{o_name}.ass") timestamp = int(time.time()) pure_video_temp = os.path.join(o_dir, f"___temp_v_{timestamp}.mkv") pure_audio_temp = os.path.join(o_dir, f"___temp_a_{timestamp}.mka") pure_sub_temp = os.path.join(o_dir, f"___temp_s_{timestamp}.ass")
has_external_audio = os.path.exists(a_in) and not a_in.startswith("【")
try: if has_external_audio: video_cmd = ['ffmpeg', '-y', '-i', v_in, '-ss', ss, '-to', to, '-map', '0:v', '-c', 'copy', pure_video_temp] else: video_cmd = ['ffmpeg', '-y', '-i', v_in, '-ss', ss, '-to', to, '-map', '0:v', '-map', '0:a?', '-c', 'copy', pure_video_temp] subprocess.run(video_cmd, check=True, capture_output=True, text=True, encoding='utf-8', errors='ignore')
if has_external_audio: audio_cmd = ['ffmpeg', '-y', '-i', a_in, '-ss', ss, '-to', to, '-c', 'copy', pure_audio_temp] subprocess.run(audio_cmd, check=True, capture_output=True, text=True, encoding='utf-8', errors='ignore')
sub_cmd = ['ffmpeg', '-y', '-ss', ss, '-to', to, '-i', s_in, '-c', 'copy', pure_sub_temp] subprocess.run(sub_cmd, check=True, capture_output=True, text=True, encoding='utf-8', errors='ignore')
if mode_idx == '1': self.make_ass_top_display(pure_sub_temp) if os.path.exists(final_ass): os.remove(final_ass) os.rename(pure_sub_temp, final_ass) if os.path.exists(pure_video_temp): os.remove(pure_video_temp) if os.path.exists(pure_audio_temp): os.remove(pure_audio_temp) elif mode_idx in ['2', '3']: merge_cmd = [mkvmerge_exe, '-o', final_mkv, pure_video_temp] if has_external_audio: merge_cmd.append(pure_audio_temp) merge_cmd.extend([ '--track-name', '0:Chs_Bottom (内置主轨)', '--default-track-flag', '0:yes', pure_sub_temp ]) result = subprocess.run(merge_cmd, capture_output=True, text=True, encoding='utf-8', errors='ignore') if result.returncode not in [0, 1]: raise RuntimeError(f"mkvmerge 错误: {result.stderr}") if os.path.exists(pure_video_temp): os.remove(pure_video_temp) if os.path.exists(pure_audio_temp): os.remove(pure_audio_temp) if mode_idx == '2': if os.path.exists(pure_sub_temp): os.remove(pure_sub_temp) elif mode_idx == '3': self.make_ass_top_display(pure_sub_temp) if os.path.exists(final_ass): os.remove(final_ass) os.rename(pure_sub_temp, final_ass)
messagebox.showinfo("大功告成", "🎉 新版黄金裁剪闭环!\n音频策略、字幕文件更名、外挂字幕全自动化【居上对齐】均已完美交付!")
except Exception as e: for p in [pure_video_temp, pure_audio_temp, pure_sub_temp]: if os.path.exists(p): os.remove(p) messagebox.showerror("错误", f"任务执行失败:\n{e}")
if __name__ == "__main__": root = tk.Tk() app = UltimateMKVToolNixClipper(root) root.mainloop()
|