返回
import os
import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import ttk
class FileUploadApp:
def __init__(self, root):
self.submit_status = False
self.text = None
self.submit_button = None
self.channel_combobox = None
self.channel_label = None
self.bit_depth_combobox = None
self.bit_depth_label = None
self.sampling_rate_combobox = None
self.sampling_rate_label = None
self.option2_radio = None
self.option1_radio = None
self.file_path_label = None
self.upload_button = None
self.root = root
self.root.title("音频提取与解码")
self.root.geometry("500x400")
# 文件路径
self.file_path = None
# 返回数据
self.return_data = {}
# 选项变量
self.option_var = tk.StringVar(value="option1")
# 初始化界面
self.init_ui()
def init_ui(self):
# 文件上传部分
self.upload_button = tk.Button(self.root, text="上传文件", command=self.upload_file)
self.upload_button.pack(pady=10)
self.file_path_label = tk.Label(self.root, text="文件路径: ")
self.file_path_label.pack()
# 单选框部分(初始隐藏)
self.option1_radio = tk.Radiobutton(
self.root, text="不指定格式", variable=self.option_var, value="option1", command=self.on_option_change
)
self.option2_radio = tk.Radiobutton(
self.root, text="指定音频格式", variable=self.option_var, value="option2", command=self.on_option_change
)
# 下拉框部分(初始隐藏)
self.sampling_rate_label = tk.Label(self.root, text="采样率")
self.sampling_rate_combobox = ttk.Combobox(self.root, values=["", "16000", "44100", "48000"], state="readonly")
self.sampling_rate_combobox.set("") # 默认值
self.bit_depth_label = tk.Label(self.root, text="解码")
self.bit_depth_combobox = ttk.Combobox(self.root, values=["pcm_u8", "pcm_s16le", "pcm_s24le",
"pcm_f32le", "adpcm_ms"], state="readonly")
self.bit_depth_combobox.set("pcm_s16le") # 默认值
self.channel_label = tk.Label(self.root, text="声道")
self.channel_combobox = ttk.Combobox(self.root, values=["", "单声道", "立体声"], state="readonly")
self.channel_combobox.set("") # 默认值
# 提交按钮
self.submit_button = tk.Button(self.root, text="提交", command=self.submit)
self.submit_button.pack(side="bottom")
def upload_file(self):
"""上传文件并显示文件路径"""
self.file_path = filedialog.askopenfilename(title="选择文件",
filetypes=[("mp3", "*.mp3"), ("mp4", "*.mp4"), ("wav", "*.wav")])
if self.file_path:
self.file_path_label.config(text=f"文件路径: {self.file_path}")
# 显示选项1和选项2
self.option1_radio.pack()
self.option2_radio.pack()
def on_option_change(self):
"""根据选项显示或隐藏下拉框"""
if self.option_var.get() == "option2":
self.sampling_rate_label.pack()
self.sampling_rate_combobox.pack()
self.bit_depth_label.pack()
self.bit_depth_combobox.pack()
self.channel_label.pack()
self.channel_combobox.pack()
else:
self.sampling_rate_label.pack_forget()
self.sampling_rate_combobox.pack_forget()
self.bit_depth_label.pack_forget()
self.bit_depth_combobox.pack_forget()
self.channel_label.pack_forget()
self.channel_combobox.pack_forget()
def submit(self):
"""提交数据并输出到控制台"""
if not self.file_path:
messagebox.showwarning("警告", "请先上传文件!")
return
else:
self.text = tk.Label(self.root, text="转码中..........", fg="red",
font=('Times', 15, 'bold italic underline'))
# 将文本内容放置在主窗口内
self.text.pack()
self.root.update() # 这里要刷新一下才显示
# 获取选中的选项
selected_option = self.option_var.get()
# 获取下拉框的值(如果选项2被选中)
if selected_option == "option2":
sampling_rate = self.sampling_rate_combobox.get()
bit_depth = self.bit_depth_combobox.get()
channel = self.channel_combobox.get()
else:
sampling_rate = bit_depth = channel = None
check_channel = {
"单声道": 1,
"立体声": 2
}
self.return_data = {
"file_path": self.file_path, # 文件地址
"selected_option": selected_option, # 选项
"sampling_rate": sampling_rate, # 采样率
"bit_depth": bit_depth, # 解码
"channel": check_channel["channel"] if channel is not None else channel,
}
self.root.quit() # 这个东西很迷,有时候能触发有时候不能触发,好像是和完成的messagebox有冲突?
return self.return_data
def main():
# 创建主窗口
root = tk.Tk()
file_upload = FileUploadApp(root)
root.mainloop()
return file_upload.return_data
=============================================================================================================================================
=============================================================================================================================================
import os
import time
import subprocess
from shutil import copyfile
from tkinter import filedialog, messagebox
from wyw.音频格式转换 import tkinter_window
from itertools import chain
class AudioFormat:
def __init__(self):
self.return_data = tkinter_window.main()
# self.file_name = ".".join(self.return_data['file_path'].split("/")[-1].split('.')[0:-1])
self.file_name = ".".join(os.path.basename(self.return_data['file_path']).split('.')[0:-1])
self.now_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
self.log = []
def run_result(self, status, input_type, output_type=None):
if status == 0:
self.log.append(f"success:{input_type}=>{output_type}")
else:
self.log.append(f"error:{input_type}=>{output_type}")
# 提取视频中的音频为wav
def mp4_to_wav(self, input_type):
if self.return_data["selected_option"] == "option1":
cmd = [
"ffmpeg",
"-i", self.return_data['file_path'],
"-vn", # 去掉视频
"-acodec", "pcm_s16le",
f"./finally/{self.now_time}/{self.file_name}.wav"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="wav")
elif self.return_data["selected_option"] == "option2":
cmd = list(chain(
["ffmpeg", "-i", self.return_data['file_path'], "-vn"],
["-acodec", str(self.return_data['bit_depth'])] if self.return_data.get('bit_depth') else ["-acodec",
"pcm_s16le"],
["-ar", str(self.return_data['sampling_rate'])] if self.return_data.get('sampling_rate') else [],
["-ac", str(self.return_data['channels'])] if self.return_data.get('channels') else [],
[f"./finally/{self.now_time}/{self.file_name}.wav"]
))
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="wav")
# 传入其他格式的音频转成wav无损格式
def audio_to_wav(self, input_type):
# 这一个用来统一格式
if self.return_data["selected_option"] == "option1":
cmd = [
"ffmpeg",
"-i", self.return_data['file_path'],
"-acodec", "adpcm_ms",
f"./finally/{self.now_time}/{self.file_name}.wav"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="wav")
elif self.return_data["selected_option"] == "option2":
cmd = list(chain(
["ffmpeg", "-i", self.return_data['file_path']],
["-acodec", str(self.return_data['bit_depth'])] if self.return_data.get('bit_depth') else ["-acodec",
"pcm_s16le"],
["-ar", str(self.return_data['sampling_rate'])] if self.return_data.get('sampling_rate') else [],
["-ac", str(self.return_data['channels'])] if self.return_data.get('channels') else [],
[f"./finally/{self.now_time}/{self.file_name}.wav"]
))
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="wav")
# 整合wav转成其他格式的
def wav_to_audio(self, input_type):
self.wav_to_mp3(input_type)
self.wav_to_aac(input_type)
self.wav_to_opus(input_type)
self.wav_to_flac(input_type)
self.wav_to_alac(input_type)
# 下面几个都是单转
def wav_to_mp3(self, input_type):
cmd = [
"ffmpeg",
"-i", f"./finally/{self.now_time}/{self.file_name}.wav",
"-acodec", "libmp3lame",
f"./finally/{self.now_time}/{self.file_name}.mp3"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="MP3")
def wav_to_aac(self, input_type):
cmd = [
"ffmpeg",
"-i", f"./finally/{self.now_time}/{self.file_name}.wav",
"-acodec", "aac",
f"./finally/{self.now_time}/{self.file_name}.aac"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="aac")
def wav_to_opus(self, input_type):
cmd = [
"ffmpeg",
"-i", f"./finally/{self.now_time}/{self.file_name}.wav",
"-acodec", "libopus",
f"./finally/{self.now_time}/{self.file_name}.opus"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="opus")
def wav_to_flac(self, input_type):
cmd = [
"ffmpeg",
"-i", f"./finally/{self.now_time}/{self.file_name}.wav",
"-acodec", "flac",
f"./finally/{self.now_time}/{self.file_name}.flac"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="flac")
def wav_to_alac(self, input_type):
cmd = [
"ffmpeg",
"-i", f"./finally/{self.now_time}/{self.file_name}.wav",
"-acodec", "alac",
f"./finally/{self.now_time}/{self.file_name}.m4a"
]
result = subprocess.run(cmd, shell=True)
self.run_result(result.returncode, input_type, output_type="alac")
def file_check(self):
# 创建文件夹位置
os.makedirs(f"./finally/{self.now_time}/", exist_ok=True)
# 判断文件类型
if self.return_data['file_path'].split('.')[-1] in ["mp3", "flac", "aac", "opus", "alac"]:
self.audio_to_wav(input_type=self.return_data['file_path'].split('.')[-1])
self.wav_to_audio(input_type=self.return_data['file_path'].split('.')[-1])
elif self.return_data['file_path'].split('.')[-1] == 'wav':
if self.return_data['selected_option'] == 'option1':
# 移动文件
copyfile(self.return_data['file_path'], f"./finally/{self.now_time}/{self.file_name}.wav")
self.wav_to_audio(input_type="wav")
else:
self.audio_to_wav(input_type="wav")
self.wav_to_audio(input_type="wav")
elif self.return_data['file_path'].split('.')[-1] in ["mp4", "avi", "mov", "mkv"]:
self.mp4_to_wav(input_type=self.return_data['file_path'].split('.')[-1])
self.wav_to_audio(input_type=self.return_data['file_path'].split('.')[-1])
messagebox.showinfo("完成", "\n".join(map(str, self.log)))
def main():
audio_format = AudioFormat()
audio_format.file_check()
if __name__ == '__main__':
main()