-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlayer.py
More file actions
636 lines (523 loc) · 24.6 KB
/
Player.py
File metadata and controls
636 lines (523 loc) · 24.6 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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import base64
import json
import logging
import os
import threading
import time
from threading import Thread
import jsonpickle
import numpy as np
import pyaudio
import spotipy
import vlc
from colorama import Fore, Style
from spotipy import SpotifyClientCredentials, SpotifyException
from websocket import WebSocketConnectionClosedException
import guard
from Song import Song
from SongsQueue import SongsQueue
from StateManager import StateManager, StateType, ActiveType
from exceptions import AgeRestrictedVideo, VideoTooLong
logger = logging.getLogger('Main')
class Player(Thread):
def __init__(self):
Thread.__init__(self)
self.comms = None
self.queue = SongsQueue()
self.instance = vlc.Instance("prefer-insecure")
self.vlc_events = None
self.VLCPlayer = self.instance.media_player_new()
self.vlc_events = self.VLCPlayer.event_manager()
self.vlc_events.event_attach(vlc.EventType.MediaPlayerEndReached, self.song_finished_callback)
self.pyAudio = None
self.stream = None
self.state: StateManager = StateManager()
# self.repeat = False
# self.force_stopped = False
# self.fetching = False
# self.currentSong = None
# self.musicPos = 0
# self.stopped = False
def run(self):
logger.info("Hello from Player")
def song_finished_callback(self, data):
logger.debug("Song finished")
self.state.set_state(StateType.SONG_FINISHED)
if self.state.repeat:
logger.debug("Song finished repeat")
self.restore_in_queue(self.state.currentSong.id, 0)
logger.debug("Song finished next")
self.state.currentSong = None
# def calc_volume(self):
# if self.currentSong:
# response = requests.get(self.state.currentSong.url,
# stream=True)
# val = 10
# # Iterate over the chunks of data and write them to a file
# rms_list = []
# for chunk in response.iter_content(chunk_size=1024):
# if chunk:
# data_np = np.frombuffer(chunk, dtype=np.int16)
#
# rms = np.sqrt(np.mean(np.square(data_np)))
# if not math.isnan(rms):
# rms_list.append(rms)
# if len(rms_list) > 100 * val:
# break
# percentage = round(len(rms_list) / val) + 1
# # if percentage <= 100:
# # sys.stdout.write(u"\u001b[1000D" + str(round(len(rms_list) / val) + 1) + "%")
# # sys.stdout.flush()
#
# plt.plot(rms_list)
# plt.title(self.currentSong.title)
# plt.xlabel('Time (chunks of 1024 samples)')
# plt.ylabel('RMS Value')
# plt.show()
# print(self.currentSong.title)
# print(max(rms_list))
# print(min(rms_list))
# print(sum(rms_list) / len(rms_list))
#
# # Define a step size for the ranges
# step = 15
#
# # Create a list of ranges
# ranges = [(i, i + step) for i in range(int(min(rms_list)), int(max(rms_list)))]
#
# # Count the number of values in each range
# counts = [len([x for x in rms_list if r[0] <= x < r[1]]) for r in ranges]
#
# # Find the index of the range with the highest count
# max_count_index = counts.index(max(counts))
#
# # Get the range with the highest count
# most_common_range = ranges[max_count_index]
#
# # Print the most common range and its count
# print(f"The most common range is {most_common_range} with a count of {max(counts)}")
def communicateBack(self, message, addTaskId=True):
if threading.current_thread().name == "CONSOLE" and addTaskId:
m = Style.BRIGHT
if message["status"] == "info":
m += Fore.LIGHTBLUE_EX
elif message["status"] == "success":
m += Fore.MAGENTA
elif message["status"] == "warning":
m += Fore.YELLOW
elif message["status"] == "error":
m += Fore.RED
else:
m += Fore.LIGHTWHITE_EX
m += message["info"]
print(m)
else:
if addTaskId:
message["taskId"] = threading.current_thread().name
try:
if self.comms:
self.comms.send(json.dumps(message))
else:
logger.fatal("Comms is None")
logger.debug("Sent back %s", message)
except WebSocketConnectionClosedException:
if guard.isInternet():
logger.warning("Socket is closed, cannot communicate back")
else:
logger.debug("Socket is closed due to no internet")
def fetch_songs_from_playlist(self, playlistId):
client_secret = "3240593b7dbc4a40b351b5e61aca2322"
client_id = "a64b981256e14d09a2cfa51f631b20d7"
try:
client_credentials_manager = SpotifyClientCredentials(client_id=client_id, client_secret=client_secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
self.communicateBack(
{"worker": "player", "action": "spotify", "cookie": "rewrite", "status": "info", "info": "Fetching..."})
total = sp.playlist_items(playlistId)["total"]
for track in sp.playlist_items(playlistId)["items"]:
name = track["track"]["name"]
artist = track["track"]["artists"][0]["name"]
total -= 1
try:
self.queue.name_add(name + " " + artist)
except AgeRestrictedVideo:
self.communicateBack(
{"worker": "queue", "action": "spotify", "cookie": "rewrite", "status": "warning",
"info": "Age restricted video"})
except VideoTooLong:
self.communicateBack(
{"worker": "queue", "action": "spotify", "cookie": "rewrite", "status": "warning",
"info": "Video too long"})
self.communicateBack(
{"worker": "player", "action": "spotify", "cookie": "rewrite", "status": "success",
"info": "Added " + name + "\nLeft " + str(total)})
self.notifyAboutQueueChange()
except SpotifyException:
self.communicateBack(
{"worker": "player", "action": "spotify", "cookie": "rewrite", "status": "error",
"info": "Playlist Id is wrong!"})
def formatSeconds(self, time):
minutes = int(time / 60)
seconds = int(time % 60)
if minutes <= 9:
minutes = "0" + str(minutes)
if seconds <= 9:
seconds = "0" + str(seconds)
return str(minutes) + ":" + str(seconds)
def set_speed(self, speed):
logger.debug("set speed request acknowledged")
if speed == 0.5:
self.VLCPlayer.set_rate(0.7)
elif speed == 0.25:
self.VLCPlayer.set_rate(0.4)
elif speed == 2:
self.VLCPlayer.set_rate(1.7)
elif speed == 1.5:
self.VLCPlayer.set_rate(1.4)
else:
self.VLCPlayer.set_rate(1)
self.state.speed = speed
def resume(self):
logger.debug("Resume request acknowledged")
if self.state.can_play():
self.VLCPlayer.set_pause(False)
self.state.set_state(StateType.PLAYING)
def play(self, isNext=False):
logger.debug("Play request acknowledged")
state = self.state.get_state()
if not self.state.can_play():
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "error",
"info": "Cannot play now"})
return
isPlaying = self.VLCPlayer.is_playing()
if isPlaying and not isNext:
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "warning",
"info": "Already playing"})
return
if state == StateType.PAUSED and not isNext: # nie gra bo zatrzymane
self.resume()
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "success",
"info": "Resuming"})
return
if self.VLCPlayer.get_state() == vlc.State.Opening and not isNext:
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "warning",
"info": "Already Fetching"})
return
else: # nie gra bo nigdy nie gralo
self.state.set_state(StateType.FETCHING)
self.send_state()
if not self.queue.is_empty() or True:
song = self.queue.peek(0)
song = "aaaaaaaaaaa"
print(song)
if song:
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "info",
"info": "Fetching..."})
logger.debug("1 in player")
# yt = YouTube("https://www.youtube.com/watch?v=" + song.id)
url = "https://idrive.pamparampam.dev/api/stream/b2kUwysAn3FsUGcjTYLwgA:1tKmMv:cJvIE7DKy74C1tQoKWfhrN8er_ePoaXHtn2xbKxUhTI?inline=True"
print(url)
logger.debug("2 in player")
logger.debug("3 in player")
logger.debug("4 in player")
media = self.instance.media_new(url)
logger.debug("5 in player")
media.get_mrl()
logger.debug("6 in player")
self.VLCPlayer.set_media(media)
logger.debug("7 in player")
self.VLCPlayer.play()
logger.debug("8 in player")
self.state.currentSong = Song(author="The Smiths", title="The Smiths - A Rush And A Push And The Land Is Ours (Official Audio)", thumbnail="aaa", length=200, id="aaa")
self.state.currentSong.url = url
while not self.VLCPlayer.is_playing:
pass
# self.queue.remove_by_index(0)
self.notifyAboutQueueChange()
self.state.set_state(StateType.PLAYING)
if isNext:
self.communicateBack(
{"worker": "player", "cookie": "rewrite", "action": "next", "status": "success",
"info": "Playing next song"})
else:
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "success",
"info": "Playing"})
else:
self.communicateBack(
{"worker": "player", "action": "play", "cookie": "rewrite", "status": "warning",
"info": "Queue is empty"})
def next(self):
self.play(True)
def toggle_repeat(self):
logger.debug("Toggle repeat request acknowledged")
self.state.repeat = not self.state.repeat
self.communicateBack(
{"worker": "player", "action": "toggle_repeat", "cookie": "rewrite", "status": "success", "info": "Toggled"})
def rewind(self):
logger.debug("Rewind request acknowledged")
self.VLCPlayer.set_time(0)
def pauseFadeout(self):
logger.debug("Pause fadeout request acknowledged")
if self.VLCPlayer.is_playing():
self.communicateBack(
{"worker": "player", "action": "stop", "cookie": "rewrite", "status": "info", "info": "Pausing..."})
volume = self.VLCPlayer.audio_get_volume()
for x in range(100):
self.VLCPlayer.audio_set_volume(int(volume - (volume / 100) * x))
time.sleep(0.03)
self.VLCPlayer.set_pause(True)
self.state.set_state(StateType.PAUSED)
self.VLCPlayer.audio_set_volume(volume)
self.communicateBack(
{"worker": "player", "action": "stop", "cookie": "rewrite", "status": "success", "info": "Paused"})
else:
self.communicateBack(
{"worker": "player", "action": "stop", "cookie": "rewrite", "status": "warning",
"info": "Nothing is playing"})
def pause(self):
logger.debug("Pause request acknowledged")
if self.VLCPlayer.is_playing():
self.VLCPlayer.set_pause(True)
self.state.set_state(StateType.PAUSED)
self.communicateBack(
{"worker": "player", "action": "stop", "cookie": "rewrite", "status": "success", "info": "Paused"})
else:
self.communicateBack(
{"worker": "player", "action": "stop", "cookie": "rewrite", "status": "warning",
"info": "Nothing is playing"})
def seek_functionality(self, seconds):
if self.state.get_state() in (StateType.PAUSED, StateType.FORCE_PAUSED, StateType.FORCE_STOPPED) or not self.VLCPlayer.is_playing():
self.communicateBack(
{"worker": "player", "action": "seek", "cookie": "rewrite", "status": "warning", "info": "Play music first"})
return
self.VLCPlayer.set_time(int(seconds * 1000))
self.communicateBack(
{"worker": "player", "action": "stop", "cookie": "rewrite", "status": "success",
"info": "Sought to " + str(self.formatSeconds(seconds))})
def seek(self, slideValue):
logger.debug("Seek request acknowledged")
if not (0 <= slideValue <= 10000):
self.communicateBack(
{"worker": "player", "action": "seek", "cookie": "rewrite", "status": "error", "info": "slideValue must be between 0 and 100000"})
return
seconds = slideValue * round(self.get_length() / 1000) / 10000
self.seek_functionality(seconds)
def set_volume(self, volume):
logger.debug("Set volume request acknowledged")
try:
if 0 <= volume <= 100:
self.VLCPlayer.audio_set_volume(volume)
self.communicateBack(
{"worker": "player", "action": "set_volume", "cookie": "rewrite", "status": "success",
"info": "Set volume to " + str(volume)})
except TypeError:
pass
def get_volume(self):
logger.debug("Get volume request acknowledged")
self.communicateBack(
{"worker": "player", "action": "set_volume", "cookie": "rewrite", "status": "success",
"volume": round(self.VLCPlayer.audio_get_volume())})
def get_repeat(self):
self.communicateBack(
{"worker": "queue", "action": "get_repeat", "cookie": "rewrite", "status": "success", "state": self.state.repeat})
def add_to_queue(self, videoId):
logger.debug("Add to queue request acknowledged")
try:
self.queue.add(videoId)
song = self.queue.get_by_id(videoId)
self.communicateBack(
{"worker": "queue", "action": "add", "cookie": "rewrite", "status": "success",
"info": "Added " + song.title})
self.notifyAboutQueueChange()
except AgeRestrictedVideo:
self.communicateBack(
{"worker": "queue", "action": "add", "cookie": "rewrite", "status": "warning",
"info": "Age restricted video"})
except VideoTooLong:
self.communicateBack(
{"worker": "queue", "action": "add", "cookie": "rewrite", "status": "warning", "info": "Video too long"})
def notifyAboutQueueChange(self):
logger.debug("Notify about queue change request acknowledged")
jsonString = jsonpickle.encode(self.queue)
try:
with open(os.getcwd() + '/queue.json', 'w') as f:
f.write(jsonString)
logger.debug("wrote %s", jsonString)
except FileNotFoundError:
logging.warning("No such file or directory: 'queue.json'")
except PermissionError:
logging.warning("Permission denied: 'queue.json'")
json_str = [ob.__dict__ for ob in self.queue.songs]
message = {"taskId": 200_000, "status": "success", "info": "all working fine", "queue": json_str}
self.communicateBack(message, addTaskId=False)
def remove_from_queue(self, videoId):
logger.debug("Remove from queue request acknowledged")
try:
song = self.queue.get_by_id(videoId)
if song:
self.queue.remove_by_id(videoId)
self.communicateBack(
{"worker": "queue", "action": "remove", "cookie": "rewrite", "status": "success",
"info": "Removed " + song.title})
self.notifyAboutQueueChange()
else:
raise ValueError
except ValueError:
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "error", "info": "Wrong videoId"})
def move_by_id_in_queue(self, videoId, position):
logger.debug("Move by id in queue request acknowledged")
try:
self.queue.move_by_id(videoId, position)
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "success", "info": "Moved"})
self.notifyAboutQueueChange()
except KeyError:
pass
except TypeError:
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "error", "info": "Type Error"})
except ValueError:
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "error",
"info": "List index out of range"})
def move_in_queue(self, starting_i, ending_i):
logger.debug("Move in queue request acknowledged")
try:
self.queue.move(starting_i, ending_i)
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "success", "info": "Moved"})
self.notifyAboutQueueChange()
except TypeError:
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "error", "info": "Type Error"})
except ValueError:
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "error",
"info": "List index out of range"})
def empty_queue(self):
logger.debug("Empty queue request acknowledged")
self.queue.empty()
self.communicateBack(
{"worker": "queue", "action": "move", "cookie": "rewrite", "status": "success", "info": "Emptied queue"})
self.notifyAboutQueueChange()
def get_length(self):
return self.VLCPlayer.get_length()
def restore_in_queue(self, videoId, position):
logger.debug("Restore in queue request acknowledged")
try:
self.queue.restore(videoId, position)
song = self.queue.peek(position)
self.communicateBack(
{"worker": "queue", "action": "restore", "cookie": "rewrite", "status": "success",
"info": "Added " + song.title})
self.notifyAboutQueueChange()
except AgeRestrictedVideo:
self.communicateBack(
{"worker": "queue", "action": "restore", "cookie": "rewrite", "status": "warning",
"info": "Age restricted video"})
except VideoTooLong:
self.communicateBack(
{"worker": "queue", "action": "restore", "cookie": "rewrite", "status": "warning",
"info": "Video too long"})
def ding_dong(self):
logger.debug("Ding Dong request acknowledged")
if self.state.get_active() != ActiveType.PLAYER:
return
self.state.set_state(StateType.FORCE_PAUSED)
self.pause()
self.state.set_active(ActiveType.DING_DONG)
mp3_file_path = "assets/ding-dong.mp3"
p = vlc.MediaPlayer(mp3_file_path)
p.play()
time.sleep(4)
if guard.canPlay():
prev_state = self.state.get_previous_state()
if prev_state != StateType.PAUSED:
self.resume()
else:
self.state.set_state(prev_state)
def start_microphone(self):
logger.debug("Start microphone request acknowledged")
if not self.state.canStartMicrophone():
self.communicateBack(
{"worker": "microphone", "action": "start", "cookie": "rewrite", "status": "error",
"info": "Cannot start microphone"})
return
self.state.set_active(ActiveType.DING_DONG)
self.send_state()
self.pyAudio = pyaudio.PyAudio()
SAMPLE_RATE = 16000
CHUNK = 1024
self.stream = self.pyAudio.open(format=pyaudio.paInt16,
channels=1,
rate=SAMPLE_RATE,
output=True,
frames_per_buffer=CHUNK)
self.state.set_state(StateType.FORCE_PAUSED)
self.pause()
mp3_file_path = "assets/ding-dong.mp3"
p = vlc.MediaPlayer(mp3_file_path)
p.play()
self.communicateBack(
{"worker": "microphone", "action": "start", "cookie": "rewrite", "status": "success",
"info": "Started Microphone"})
time.sleep(4)
self.state.set_active(ActiveType.MICROPHONE)
def stop_microphone(self):
logger.debug("Stop microphone request acknowledged")
if self.state.get_active() != ActiveType.MICROPHONE:
self.communicateBack(
{"worker": "microphone", "action": "start", "cookie": "rewrite", "status": "error",
"info": "Can't stop: microphone is not active"})
self.state.set_state(self.state.get_previous_state())
return
self.pyAudio = None
if self.stream:
self.stream.stop_stream()
self.stream = None
self.state.set_active(ActiveType.PLAYER)
if guard.canPlay():
prev_state = self.state.get_previous_state()
if prev_state != StateType.PAUSED:
self.resume()
else:
self.state.set_state(prev_state)
self.communicateBack(
{"worker": "microphone", "action": "start", "cookie": "rewrite", "status": "success",
"info": "Stopped Microphone"})
def process_microphone(self, bytes_data):
logger.debug("Process microphone request acknowledged")
if not self.stream:
return
# if not guard.isBreakNow():
# self.stop_microphone()
# return
audio_data = base64.b64decode(bytes_data) # Convert Base64 back to bytes
# Convert bytes to numpy array (assuming 16-bit audio)
audio_samples = np.frombuffer(audio_data, dtype=np.int16)
# Adjust volume (e.g., 0.5 for 50% volume, 1.5 for 150% volume)
volume_multiplier = self.VLCPlayer.audio_get_volume() / 50
adjusted_samples = (audio_samples * volume_multiplier).astype(np.int16)
# Convert back to bytes
adjusted_audio_data = adjusted_samples.tobytes()
self.stream.write(adjusted_audio_data) # Directly play the incoming bytes
def send_state(self):
length = self.get_length()
if self.state.currentSong and length:
FormattedPos = self.formatSeconds(round(self.VLCPlayer.get_time() / 1000))
FormattedLength = self.formatSeconds(length / 1000)
b = round((self.VLCPlayer.get_time() * 10000) / length)
self.communicateBack(
{"worker": "player", "action": "get_state", "pos": b, "title": self.state.getStateMessage(), "taskId": 100_000,
"length": FormattedLength, "seconds": FormattedPos}, False)
else:
self.communicateBack(
{"worker": "player", "action": "get_state", "pos": 0, "status": "success", "title": self.state.getStateMessage(), "taskId": 100_000,
"length": "00:00", "seconds": "00:00"}, False)