MySafeCode commited on
Commit
5193b85
·
verified ·
1 Parent(s): 2eadd2b

Create a.py

Browse files
Files changed (1) hide show
  1. a.py +53 -0
a.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from yt_dlp import YoutubeDL
3
+ import os
4
+ from pydub import AudioSegment
5
+
6
+ DOWNLOADS_FOLDER = "downloads"
7
+ os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)
8
+
9
+ def download_soundcloud(url, file_format, duration_sec):
10
+ # Download best audio first (usually m4a)
11
+ ydl_opts = {
12
+ 'format': 'bestaudio/best',
13
+ 'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s')
14
+ }
15
+
16
+ with YoutubeDL(ydl_opts) as ydl:
17
+ info = ydl.extract_info(url, download=True)
18
+
19
+ original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")
20
+
21
+ # Load audio and trim to duration
22
+ audio = AudioSegment.from_file(original_file)
23
+ duration_ms = min(len(audio), int(duration_sec * 1000))
24
+ trimmed_audio = audio[:duration_ms]
25
+
26
+ # Determine output file path
27
+ if file_format.lower() == "mp3":
28
+ output_file = os.path.splitext(original_file)[0] + ".mp3"
29
+ trimmed_audio.export(output_file, format="mp3")
30
+ elif file_format.lower() == "opus":
31
+ output_file = os.path.splitext(original_file)[0] + ".opus"
32
+ trimmed_audio.export(output_file, format="opus")
33
+ else: # keep original format
34
+ output_file = os.path.splitext(original_file)[0] + f".{info['ext']}"
35
+ trimmed_audio.export(output_file, format=info['ext'])
36
+
37
+ return output_file
38
+
39
+ # Gradio interface
40
+ with gr.Blocks() as iface:
41
+ url_input = gr.Textbox(label="SoundCloud URL", value="https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover")
42
+ format_choice = gr.Dropdown(choices=["mp3", "m4a", "opus"], value="mp3", label="Select format")
43
+ duration_slider = gr.Slider(minimum=5, maximum=300, value=30, step=5, label="Duration (seconds)")
44
+ download_button = gr.Button("Download")
45
+ download_file = gr.File(label="Download your track")
46
+
47
+ download_button.click(
48
+ fn=download_soundcloud,
49
+ inputs=[url_input, format_choice, duration_slider],
50
+ outputs=download_file
51
+ )
52
+
53
+ iface.launch(show_error=True)