成品UI
安裝moviepy庫
pip install moviepy
轉換demo
from moviepy.editor import *# 創建一個顏色剪輯,時長與音頻相同
audioclip = AudioFileClip(r"C:\Users\Administrator\PycharmProjects\pythonProject44\test4\趙照 - 燈塔守望人.mp3")
videoclip = ColorClip((800, 600), col=(255, 255, 255), duration=audioclip.duration)# 把音頻文件添加到視頻剪輯中
videoclip = videoclip.set_audio(audioclip)# 保存視頻文件
videoclip.write_videofile("output_video.mp4", fps=24)
通過demo代碼,進行優化,實現以下功能點
- Tk界面,展示一個輸入框,輸入框展示,選擇MP3文件的完整路徑。
- 展示一個轉換按鈕,在選擇MP3文件后,點擊轉換按鈕,進行轉換時,按鈕置灰。
- 界面展示轉換狀態,點擊轉換按鈕,展示“正在轉換文本“的提示文本,轉換成功后,展示“轉換成功“的提示文本
完整代碼
import tkinter as tk
from tkinter import filedialog
from moviepy.editor import *
from threading import Threaddef select_file():file_path = filedialog.askopenfilename(filetypes=[("MP3 files", "*.mp3")])if file_path:path_entry.delete(0, tk.END)path_entry.insert(0, file_path)return file_pathdef convert():file_path = path_entry.get()# 創建一個顏色剪輯,時長與音頻相同audioclip = AudioFileClip(file_path)videoclip = ColorClip((800, 600), col=(255, 255, 255), duration=audioclip.duration)# 把音頻文件添加到視頻剪輯中videoclip = videoclip.set_audio(audioclip)# 獲取文件名,不包括擴展名base_name = os.path.basename(file_path)file_name = os.path.splitext(base_name)[0]# 保存視頻文件,文件名與音頻文件相同,保存在腳本的同一目錄下videoclip.write_videofile(f"{file_name}.mp4", fps=24)convert_button.config(state=tk.NORMAL)status_label.config(text='成功!')def start_conversion():convert_button.config(state=tk.DISABLED)status_label.config(text='正在轉換...')Thread(target=convert).start()def main():global path_entry, convert_button, status_labelroot = tk.Tk()root.geometry('500x150')path_entry = tk.Entry(root, width=40)path_entry.pack()select_button = tk.Button(root, text='Select MP3', command=select_file)select_button.pack()convert_button = tk.Button(root, text='Convert', command=start_conversion)convert_button.pack()status_label = tk.Label(root, text='')status_label.pack()root.mainloop()if __name__ == "__main__":main()
安裝pyinstaller庫
把py腳本打包為exe程序
pip install pyinstaller
pyinstaller -w --onefile C:\Users\Administrator\PycharmProjects\pythonProject44\test6\MP3zhuanmp4.py
文章已上傳打包附件?