Spaces:
Sleeping
Sleeping
Update youtube_video.py
Browse files- youtube_video.py +37 -34
youtube_video.py
CHANGED
@@ -1,34 +1,37 @@
|
|
1 |
-
import pytube
|
2 |
-
import os
|
3 |
-
from pytube import YouTube
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
|
1 |
+
import pytube
|
2 |
+
import os
|
3 |
+
from pytube import YouTube
|
4 |
+
|
5 |
+
def download_youtube_audio(youtube_url):
|
6 |
+
"""Downloads the audio from a YouTube video, renames it to the first twelve characters, and returns the downloaded file path."""
|
7 |
+
|
8 |
+
try:
|
9 |
+
# Create a YouTube object
|
10 |
+
yt = YouTube(youtube_url)
|
11 |
+
|
12 |
+
# Get the audio stream
|
13 |
+
audio = yt.streams.filter(only_audio=True).first()
|
14 |
+
|
15 |
+
# Download the audio
|
16 |
+
print("Downloading...")
|
17 |
+
audio.download()
|
18 |
+
|
19 |
+
# Get the original filename
|
20 |
+
original_filename = audio.default_filename
|
21 |
+
|
22 |
+
# Extract the first twelve characters and change the file extension to .mp3
|
23 |
+
new_filename = original_filename[:12] + '.mp3'
|
24 |
+
|
25 |
+
# Rename the downloaded file
|
26 |
+
os.rename(original_filename, new_filename)
|
27 |
+
|
28 |
+
print("Download complete! Audio saved to:", new_filename)
|
29 |
+
return new_filename
|
30 |
+
|
31 |
+
except Exception as e:
|
32 |
+
print("An error occurred:", e)
|
33 |
+
return None
|
34 |
+
|
35 |
+
# Example usage
|
36 |
+
youtube_url = "https://www.youtube.com/watch?v=your_video_id"
|
37 |
+
download_youtube_audio(youtube_url)
|