import gradio as gr from pydub import AudioSegment import os def mix_audio(podcast_file, bgm_file, bgm_volume, loop, fade_in_out, fade_duration): if not podcast_file or not bgm_file: return "請上傳 Podcast 和 BGM 檔案", None # 讀取音檔 podcast = AudioSegment.from_file(podcast_file) bgm = AudioSegment.from_file(bgm_file) # 調整 BGM 音量 bgm = bgm - abs(bgm_volume) # 降低 dB # 是否需要 loop BGM if loop: loop_count = len(podcast) // len(bgm) + 1 bgm = bgm * loop_count # 重複播放 bgm = bgm[:len(podcast)] # 修剪至 Podcast 長度 # 是否添加淡入淡出效果 if fade_in_out: bgm = bgm.fade_in(fade_duration * 1000).fade_out(fade_duration * 1000) # 混音 mixed = podcast.overlay(bgm) # 儲存混音結果 output_file = "mixed_podcast.mp3" mixed.export(output_file, format="mp3") return "混音完成!點擊下載", output_file, output_file # 第三個值是給 gr.Audio 用的 # 建立 Gradio 介面 with gr.Blocks() as app: gr.Markdown("## 🎙️ Podcast 混音工具 🎵") with gr.Row(): with gr.Column(): podcast_input = gr.File(label="🎙️ 上傳 Podcast MP3", type="filepath") bgm_input = gr.File(label="🎵 上傳背景音樂 MP3", type="filepath") bgm_volume = gr.Slider(-30, 0, value=-14, label="🎚️ 背景音樂音量調整 (dB, 越小越小聲)") loop_option = gr.Checkbox(value=True, label="🔁 背景音樂循環") fade_option = gr.Checkbox(value=True, label="🎼 添加淡入淡出效果") fade_duration = gr.Slider(1, 10, value=5, label="⏳ 淡入淡出秒數") process_button = gr.Button("🚀 開始混音") with gr.Column(): output_message = gr.Textbox(label="📢 處理狀態", interactive=False) audio_output = gr.Audio(label="🎧 預覽混音結果", format="mp3", interactive=False, autoplay=False) download_output = gr.File(label="⬇️ 下載混音 MP3") process_button.click( fn=mix_audio, inputs=[podcast_input, bgm_input, bgm_volume, loop_option, fade_option, fade_duration], outputs=[output_message, audio_output, download_output] # 確保 Audio 正確顯示 ) # 執行 Gradio 應用 app.launch()