-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMelody_CLI.py
279 lines (227 loc) · 8.37 KB
/
Melody_CLI.py
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import os
import pygame
import threading
import time
from yt_dlp import YoutubeDL
from ytmusicapi import YTMusic
from pydub import AudioSegment
class Player():
def __init__(self) -> None:
"""
Initialize the Player class.
Attributes:
-----------
youtube_music : YTMusic
An instance of YTMusic class for interacting with YouTube Music.
index : int
A counter to keep track of the search results.
filtered_results : dict
A dictionary to store the filtered search results.
currently_playing : str
The currently playing song's file path.
playback_thread : threading.Thread
A thread for playing the song.
is_paused : bool
A flag to indicate whether the song is paused.
BASE_URL : str
The base URL for YouTube video links.
"""
self.youtube_music = YTMusic()
self.index = 1
self.filtered_results = {}
self.currently_playing = None
self.playback_thread = None
self.is_paused = False
self.BASE_URL = 'https://www.youtube.com/watch?v='
def searchSong(self, searchString):
"""
Searches for a song on YouTube Music using the provided search string.
Parameters:
searchString (str): The search string to be used for searching the song.
Returns:
dict, dict: A dictionary containing the search results and another dictionary containing the filtered search results.
Raises:
Exception: If the search results are empty.
Example:
>>> player = Player()
>>> search_results, filtered_results = player.searchSong("song title")
"""
searches = {}
search_results = self.youtube_music.search(searchString)
for search in search_results:
if(search["category"] == 'Songs' or search["category"] == "Videos"):
self.filtered_results[self.index] = search['videoId']
searches["Title"] = search['title']
searches["Type"] = search['resultType']
searches["Duration"] = search['duration']
searches["Video-ID"] = search['videoId']
searches["Artists"] = search['artists']
self.index += 1
return searches, self.filtered_results
def downloadSong(self, videoID):
"""
Downloads the audio file of the specified YouTube video.
Parameters:
videoID (str): The unique identifier of the YouTube video.
Returns:
str: The path to the downloaded audio file.
Raises:
Exception: If an error occurs during the download or conversion process.
Example:
>>> player = Player()
>>> audio_file = player.downloadSong("video_id")
"""
url = f"{self.BASE_URL}{str(videoID)}"
os.makedirs("temp_audio", exist_ok=True)
t = time.time()
ml = int(t * 1000)
ydl_opts = {
'format': 'bestaudio/best',
'outtmpl': f'temp_audio/Audio_{videoID + str(t)}.%(ext)s',
'quiet': True,
'no_warnings': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'wav',
'preferredquality': '192',
}],
}
try:
with YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
audio_file = f'temp_audio/Audio_{videoID + str(t)}.wav'
print(f"Download and conversion complete: {audio_file}")
return audio_file
except Exception as e:
print(f"Error: {e}")
m4a_file = f'temp_audio/Audio_{videoID + str(t)}.m4a'
wav_filename = f'temp_audio/Audio_{videoID + str(t)}.wav'
sound = AudioSegment.from_file(m4a_file, format='m4a')
sound.export(wav_filename, format='wav')
os.remove(m4a_file)
return wav_filename
def playSong(self, mp3_file):
"""
Plays the specified audio file using the Pygame library.
Parameters:
mp3_file (str): The path to the audio file to be played.
Returns:
None
Raises:
Exception: If an error occurs during the playback process.
Example:
>>> player = Player()
>>> player.playSong("path_to_audio_file.mp3")
"""
def _play():
"""
Internal function to initialize Pygame, load the audio file, and start playback.
Parameters:
None
Returns:
None
Raises:
Exception: If an error occurs during the playback process.
"""
#pygame.init()
#pygame.mixer.init()
pygame.mixer.music.load(mp3_file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() or self.is_paused:
pygame.time.Clock().tick(10)
self.stopSong(mp3_file)
self.currently_playing = mp3_file
self.playback_thread = threading.Thread(target=_play)
self.playback_thread.start()
def pauseSong(self):
"""
Pauses the currently playing song if it is not already paused.
Parameters:
None
Returns:
None
Raises:
Exception: If there is no currently playing song.
Example:
>>> player = Player()
>>> player.playSong("path_to_audio_file.mp3")
>>> player.pauseSong()
"""
if self.currently_playing and not self.is_paused:
pygame.mixer.music.pause()
self.is_paused = True
print("Music paused")
def resumeSong(self):
"""
Resumes the currently playing song if it is paused.
Parameters:
None
Returns:
None
Raises:
Exception: If there is no currently playing song.
Example:
>>> player = Player()
>>> player.playSong("path_to_audio_file.mp3")
>>> player.pauseSong()
>>> player.resumeSong()
"""
if self.currently_playing and self.is_paused:
pygame.mixer.music.unpause()
self.is_paused = False
print("Music resumed")
def removetempfile(self, audioFile):
# Try to delete the file.
try:
pygame.mixer.music.unload()
os.remove(audioFile)
print("Temporary file is deleted:", audioFile)
except OSError as e:
# If it fails, inform the user.
print("Error: %s - %s." % (e.filename, e.strerror))
def stopSong(self, mp3_file):
"""
Stops the currently playing song and resets the player's state.
Parameters:
None
Returns:
None
Raises:
Exception: If there is no currently playing song.
Example:
>>> player = Player()
>>> player.playSong("path_to_audio_file.mp3")
>>> player.stopSong()
"""
if self.currently_playing:
pygame.mixer.music.stop()
self.removetempfile(mp3_file)
self.currently_playing = None
self.is_paused = False
def addvolumeSong(self, addvol):
currentvol = pygame.mixer.music.get_volume()
pygame.mixer.music.set_volume(addvol+currentvol)
editvol = pygame.mixer.music.get_volume()
return editvol
def setvolumeSong(self, setvol):
pygame.mixer.music.set_volume(setvol)
editvol = pygame.mixer.music.get_volume()
return editvol
def unloadSong(self):
"""
Stops the currently playing song and resets the player's state.
Parameters:
None
Returns:
None
Raises:
Exception: If there is no currently playing song.
Example:
>>> player = Player()
>>> player.playSong("path_to_audio_file.mp3")
>>> player.stopSong()
"""
if not self.currently_playing:
pygame.mixer.music.unload()
self.currently_playing = None
self.is_paused = False