
import os
import subprocess
import sys
def clean_path(path_str):
"""清理拖拽文件时终端自动添加的引号和多余空格"""
return path_str.strip(' "\'')
def process_audio():
# 【核心升级】判断当前是 Python 脚本运行,还是被打包成了 exe 运行
# 确保导出的文件永远保存在程序所在的当前目录
if getattr(sys, 'frozen', False):
script_dir = os.path.dirname(sys.executable)
else:
script_dir = os.path.dirname(os.path.abspath(__file__))
print("="*50)
print("⚖️ 无损截取工具 ")
print("="*50)
while True:
print("\n【第一步:选择文件】")
user_input = input("▶ 请直接将音频文件拖拽到此窗口,然后按回车 (输入 q 退出): ").strip()
if user_input.lower() == 'q':
break
if not user_input:
continue
input_path = clean_path(user_input)
if not os.path.exists(input_path):
print(f"❌ 找不到文件:{input_path},请重新拖拽!")
continue
print(f"\n✅ 已选中文件: {os.path.basename(input_path)}")
# 获取开始和结束时间
print("\n【第二步:设置时间】")
print("支持的格式:纯秒数 (如 930) 或 时分秒 (如 00:15:30)")
start_time = input("请输入【开始】时间: ").strip()
end_time = input("请输入【结束】时间: ").strip()
if not start_time or not end_time:
print("❌ 时间不能为空,请重新开始。")
continue
# 自动生成导出文件名 (保存在程序同级目录)
base_name, ext = os.path.splitext(os.path.basename(input_path))
safe_start = start_time.replace(':', '')
safe_end = end_time.replace(':', '')
output_filename = f"{base_name}_截取_{safe_start}至{safe_end}{ext}"
output_path = os.path.join(script_dir, output_filename)
print("\n【第三步:开始无损截取...】")
command = [
"ffmpeg",
"-i", input_path,
"-ss", start_time,
"-to", end_time,
"-c", "copy",
"-y", # 如果文件已存在则覆盖
output_path
]
try:
# 执行 FFmpeg 命令
subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f"🎉 截取成功!")
print(f"📁 文件已无损保存至: {output_path}")
except FileNotFoundError:
print("❌ 致命错误:系统中未找到 FFmpeg!")
print("请确保已将 ffmpeg.exe 与本程序放在同一文件夹下,或配置了环境变量。")
except subprocess.CalledProcessError as e:
print(f"❌ 截取失败,FFmpeg 报错:\n{e.stderr.decode('utf-8', errors='ignore')}")
print("\n" + "-"*50)
if __name__ == "__main__":
try:
process_audio()
except KeyboardInterrupt:
print("\n已退出程序。")
sys.exit(0)