-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyt_audio.py
More file actions
42 lines (34 loc) · 1.25 KB
/
yt_audio.py
File metadata and controls
42 lines (34 loc) · 1.25 KB
1
2
3
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
35
36
37
38
39
40
41
42
import yt_dlp
from pydub import AudioSegment
import os
def youtube_to_audio(url, output_format='mp3', output_folder='downloads'):
os.makedirs(output_folder, exist_ok=True)
# Temp audio download
temp_file = os.path.join(output_folder, "temp_audio.webm")
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': temp_file,
'quiet': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=True)
title = info.get('title', 'audio')
# Convert with pydub
audio = AudioSegment.from_file(temp_file)
output_path = os.path.join(output_folder, f"{title}.{output_format}")
if output_format == 'mp3':
audio.export(output_path, format='mp3', bitrate='192k')
elif output_format == 'wav':
audio.export(
output_path,
format='wav',
parameters=['-acodec', 'pcm_s16le', '-ac', '1', '-ar', '11025']
)
else:
raise ValueError("Output format must be 'mp3' or 'wav'")
os.remove(temp_file)
print(f"Saved: {output_path}")
return output_path
#https://www.youtube.com/watch?v=A8wK-vhuWog, https://www.youtube.com/watch?v=miZHa7ZC6Z0
#run
youtube_to_audio("https://www.youtube.com/watch?v=A8wK-vhuWog", output_format="wav")