import yt_dlp import gradio as gr import os from glob import glob def convert_time_to_seconds(time_str): hours, minutes, seconds = map(int, time_str.split(':')) return hours * 3600 + minutes * 60 + seconds def download_video(video_url, start_time, end_time): start_seconds = convert_time_to_seconds(start_time) end_seconds = convert_time_to_seconds(end_time) options = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '128', }], 'outtmpl': '%(title)s.%(ext)s', 'postprocessor_args': [ '-ss', str(start_seconds), '-to', str(end_seconds) ] } with yt_dlp.YoutubeDL(options) as ydl: ydl.download([video_url]) # 查找和提供下载的文件 download_files = glob('*.mp3') if download_files: return f"Download successful: {download_files[0]}", download_files[0] return "No MP3 file found.", None def setup_interface(): interface = gr.Interface( fn=download_video, inputs=[ gr.Textbox(lines=2, placeholder="Enter YouTube video URL here...", label="YouTube Video URL"), gr.Textbox(placeholder="Start Time (e.g., 00:00:00)", label="Start Time (HH:MM:SS)"), gr.Textbox(placeholder="End Time (e.g., 00:05:30)", label="End Time (HH:MM:SS)") ], outputs=[ gr.Text(label="Status Message"), gr.File(label="Download MP3") ], title="YouTube Video Downloader", description="Enter YouTube video URL and specify start and end times to download audio as MP3." ) return interface if __name__ == "__main__": iface = setup_interface() iface.launch()