-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathytToMp3.py
More file actions
109 lines (98 loc) · 4.09 KB
/
ytToMp3.py
File metadata and controls
109 lines (98 loc) · 4.09 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import os
import yt_dlp
from dotenv import load_dotenv
from googleapiclient.discovery import build
# This script provides a class to interact with the YouTube API for downloading audio from YouTube videos as MP3 files.
load_dotenv() # Loads variables from .env into environment
API_KEY = os.getenv("API_KEY")
class YouTubeAPI:
def __init__(self, wav_data_dir="wavData", default_output_path="."):
self.wav_data_dir = wav_data_dir
self.default_output_path = default_output_path
def download_youtube_as_mp3(self, youtube_url, output_path=None):
if output_path is None:
output_path = self.default_output_path
# Get video info first to check for duplicate files
try:
with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
info = ydl.extract_info(youtube_url, download=False)
title = info.get('title', 'unknown_title')
existing_files = os.listdir(self.wav_data_dir)
for fname in existing_files:
if fname[2:-4] == title:
print(f"File '{title}' already exists. Skipping download.")
return
except yt_dlp.utils.DownloadError as e:
print(f"Error fetching video info: {e}")
return
except Exception as e:
print(f"An unexpected error occurred: {e}")
return
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f'{output_path}/%(title)s.%(ext)s',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'quiet': False,
'noplaylist': True,
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([youtube_url])
print("Download and conversion successful.")
except yt_dlp.utils.DownloadError as e:
print(f"Download error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
def search_youtube(self, query, max_results=1):
ydl_opts = {
'quiet': True,
'skip_download': True,
'extract_flat': True,
'default_search': 'ytsearch',
'noplaylist': True
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
result = ydl.extract_info(f"ytsearch{max_results}:{query}", download=False)
if 'entries' in result and result['entries']:
return [entry['url'] for entry in result['entries']]
else:
return []
def search_youtube_official(self, query, max_results=5):
youtube = build('youtube', 'v3', developerKey=API_KEY)
video_urls = []
next_page_token = None
fetched = 0
while fetched < max_results:
to_fetch = min(50, max_results - fetched)
request = youtube.search().list(
part='snippet',
q=query,
type='video',
order='relevance', # date, rating, relevance, title, videoCount, viewCount
videoCategoryId='10', # music
videoDuration='short', # videos < 4 minutes
regionCode="US", # Prioritize US content
relevanceLanguage="en", # Prioritize English-language metadata
maxResults=to_fetch,
pageToken=next_page_token
)
response = request.execute()
items = response.get('items', [])
video_urls.extend(
f"https://www.youtube.com/watch?v={item['id']['videoId']}"
for item in items
)
fetched += len(items)
next_page_token = response.get('nextPageToken')
if not next_page_token or len(items) == 0:
break
return video_urls[:max_results]
# Example usage:
# downloader = YouTubeAPI()
# urls = downloader.search_youtube("Rick Astley Never Gonna Give You Up")
# if urls:
# downloader.download_youtube_as_mp3(urls[0])