import gradio as gr from yt_dlp import YoutubeDL import os from pydub import AudioSegment DOWNLOADS_FOLDER = "downloads" os.makedirs(DOWNLOADS_FOLDER, exist_ok=True) def download_soundcloud(url, file_format, duration_sec): # Download best audio first (usually m4a) ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s') } with YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}") # Load audio and trim to duration audio = AudioSegment.from_file(original_file) duration_ms = min(len(audio), int(duration_sec * 1000)) trimmed_audio = audio[:duration_ms] # Determine output file path if file_format.lower() == "mp3": output_file = os.path.splitext(original_file)[0] + ".mp3" trimmed_audio.export(output_file, format="mp3") elif file_format.lower() == "opus": output_file = os.path.splitext(original_file)[0] + ".opus" trimmed_audio.export(output_file, format="opus") else: # keep original format output_file = os.path.splitext(original_file)[0] + f".{info['ext']}" trimmed_audio.export(output_file, format=info['ext']) return output_file # Gradio interface with gr.Blocks() as iface: url_input = gr.Textbox(label="SoundCloud URL", value="https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover") format_choice = gr.Dropdown(choices=["mp3", "m4a", "opus"], value="mp3", label="Select format") duration_slider = gr.Slider(minimum=5, maximum=300, value=30, step=5, label="Duration (seconds)") download_button = gr.Button("Download") download_file = gr.File(label="Download your track") download_button.click( fn=download_soundcloud, inputs=[url_input, format_choice, duration_slider], outputs=download_file ) iface.launch(show_error=True)