This repository was archived by the owner on Mar 7, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathamp.py
More file actions
1301 lines (1167 loc) · 53.5 KB
/
amp.py
File metadata and controls
1301 lines (1167 loc) · 53.5 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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt
def setup_vlc_dependencies():
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(__file__)
vlc_base = os.path.join(base_path, "vlc")
required = {"libvlc.dll", "libvlccore.dll"}
dll_dir = None
for root, _, files in os.walk(vlc_base):
if required.issubset(files):
dll_dir = root
break
if dll_dir:
os.environ["PATH"] = dll_dir + os.pathsep + os.environ.get("PATH", "")
print("Using bundled VLC in:", dll_dir)
else:
raise FileNotFoundError(f"VLC binaries not found under {vlc_base}")
setup_vlc_dependencies()
import importlib.util
import vlc
from PyQt5.QtCore import QTimer, QModelIndex, QSettings, QObject, pyqtSignal
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import (
QMainWindow, QAction, QWidget, QVBoxLayout, QHBoxLayout, QDockWidget, QTreeView,
QFileDialog, QFileSystemModel, QPushButton, QSlider, QLabel, QStatusBar,
QSystemTrayIcon, QMenu, QListWidget, QListWidgetItem, QDialog, QComboBox,
QCheckBox, QGridLayout, QGroupBox
)
try:
from mutagen import File as MutagenFile
except ImportError:
MutagenFile = None
class VLCMediaPlayer(QObject):
positionChanged = pyqtSignal(int)
durationChanged = pyqtSignal(int)
mediaEnded = pyqtSignal()
def __init__(self, parent=None):
super().__init__(parent)
self.instance = vlc.Instance("--no-video")
self.player = self.instance.media_player_new()
self.player.video_set_track(-1)
self._duration = 0
self._current_media = None
self._media_ended = False
self.poll_timer = QTimer(self)
self.poll_timer.setInterval(100)
self.poll_timer.timeout.connect(self._poll)
self.poll_timer.start()
events = self.player.event_manager()
events.event_attach(vlc.EventType.MediaPlayerEndReached, self._on_media_end)
self.equalizer = None
self._eq_enabled = False
def _poll(self):
duration = self.player.get_length()
if duration != self._duration:
self._duration = duration
self.durationChanged.emit(duration)
pos = self.player.get_time()
self.positionChanged.emit(pos)
if duration > 0 and pos > 0 and not self._media_ended:
if pos >= duration - 50:
self._media_ended = True
self.mediaEnded.emit()
def set_media(self, file_path):
media = self.instance.media_new(file_path)
self.player.set_media(media)
self._current_media = file_path
self._media_ended = False
self.player.video_set_track(-1)
def _on_media_end(self, event):
if not self._media_ended:
self._media_ended = True
self.mediaEnded.emit()
def play(self):
self.player.play()
def pause(self):
self.player.pause()
def stop(self):
self.player.stop()
def set_position(self, position):
duration = self.get_duration()
if duration > 0:
fraction = position / duration
self.player.set_position(fraction)
def get_position(self):
return self.player.get_time()
def get_duration(self):
return self.player.get_length()
def set_volume(self, volume):
self.player.audio_set_volume(volume)
def is_playing(self):
return self.player.is_playing()
def create_equalizer(self):
if self.equalizer is None:
self.equalizer = vlc.libvlc_audio_equalizer_new()
return self.equalizer
def enable_equalizer(self, enabled=True):
if enabled:
if self.equalizer is None:
self.create_equalizer()
self.player.set_equalizer(self.equalizer)
self._eq_enabled = True
else:
self.player.set_equalizer(None)
self._eq_enabled = False
def is_equalizer_enabled(self):
return self._eq_enabled
def get_band_count(self):
return vlc.libvlc_audio_equalizer_get_band_count()
def get_band_frequency(self, band_index):
return vlc.libvlc_audio_equalizer_get_band_frequency(band_index)
def set_band_amp(self, band_index, amp):
if self.equalizer is None:
self.create_equalizer()
vlc.libvlc_audio_equalizer_set_amp_at_index(self.equalizer, amp, band_index)
if self._eq_enabled:
self.player.set_equalizer(self.equalizer)
def get_band_amp(self, band_index):
if self.equalizer is None:
return 0.0
return vlc.libvlc_audio_equalizer_get_amp_at_index(self.equalizer, band_index)
def set_preamp(self, amp):
if self.equalizer is None:
self.create_equalizer()
vlc.libvlc_audio_equalizer_set_preamp(self.equalizer, amp)
if self._eq_enabled:
self.player.set_equalizer(self.equalizer)
def get_preamp(self):
if self.equalizer is None:
return 0.0
return vlc.libvlc_audio_equalizer_get_preamp(self.equalizer)
def load_icon(icon_name):
icon_path = os.path.join(os.path.dirname(__file__), icon_name)
if getattr(sys, 'frozen', False):
icon_path = os.path.join(sys._MEIPASS, icon_name)
if os.path.exists(icon_path):
return QIcon(icon_path)
return None
def load_plugins(app_context):
user_home = os.path.expanduser("~")
plugins_dir = os.path.join(user_home, "ampplugins")
os.makedirs(plugins_dir, exist_ok=True)
loaded_plugins = []
for filename in os.listdir(plugins_dir):
if filename.endswith(".py") and not filename.startswith("_"):
plugin_path = os.path.join(plugins_dir, filename)
mod_name = os.path.splitext(filename)[0]
spec = importlib.util.spec_from_file_location(mod_name, plugin_path)
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
if hasattr(module, "register_plugin"):
module.register_plugin(app_context)
loaded_plugins.append(mod_name)
print(f"Plugin '{mod_name}' loaded successfully from {plugins_dir}")
except Exception as e:
print(f"Failed to load plugin '{filename}' from {plugins_dir}: {e}")
return loaded_plugins
def loadStyle():
user_css_path = os.path.join(os.path.expanduser("~"), "apstyle.css")
stylesheet = None
if os.path.exists(user_css_path):
try:
with open(user_css_path, 'r') as css_file:
stylesheet = css_file.read()
print(f"Loaded user CSS style from: {user_css_path}")
except Exception as e:
print(f"Error loading user CSS: {e}")
else:
css_file_path = os.path.join(os.path.dirname(__file__), 'style.css')
try:
with open(css_file_path, 'r') as css_file:
stylesheet = css_file.read()
except FileNotFoundError:
print(f"Default CSS file not found: {css_file_path}")
if stylesheet:
app = QApplication.instance()
if app:
app.setStyleSheet(stylesheet)
else:
print("No QApplication instance found. Stylesheet not applied.")
class EqualizerDialog(QDialog):
def __init__(self, media_player, parent=None):
super().__init__(parent)
self.media_player = media_player
self.setWindowTitle("Equalizer")
self.setModal(False)
self.resize(600, 500)
self.band_count = self.media_player.get_band_count()
self.band_sliders = []
self.band_labels = []
self.save_timer = QTimer(self)
self.save_timer.setSingleShot(True)
self.save_timer.setInterval(500)
self.save_timer.timeout.connect(self._save_settings)
self.init_ui()
self.load_current_settings()
def init_ui(self):
main_layout = QVBoxLayout(self)
self.enable_checkbox = QCheckBox("Enable Equalizer")
self.enable_checkbox.setChecked(self.media_player.is_equalizer_enabled())
self.enable_checkbox.stateChanged.connect(self.on_enable_changed)
main_layout.addWidget(self.enable_checkbox)
preset_layout = QHBoxLayout()
preset_layout.addWidget(QLabel("Preset:"))
self.preset_combo = QComboBox()
self.preset_combo.addItems(["Flat", "Rock", "Pop", "Jazz", "Classical", "Bass Boost", "Treble Boost", "Custom"])
self.preset_combo.currentTextChanged.connect(self.on_preset_changed)
preset_layout.addWidget(self.preset_combo)
preset_layout.addStretch()
main_layout.addLayout(preset_layout)
preamp_group = QGroupBox("Pre-amplification")
preamp_layout = QVBoxLayout()
self.preamp_slider = QSlider(Qt.Horizontal)
self.preamp_slider.setRange(-200, 200)
self.preamp_slider.setValue(0)
self.preamp_slider.setTickPosition(QSlider.TicksBelow)
self.preamp_slider.setTickInterval(50)
self.preamp_slider.valueChanged.connect(self.on_preamp_changed)
self.preamp_label = QLabel("0.0 dB")
self.preamp_label.setAlignment(Qt.AlignCenter)
preamp_layout.addWidget(self.preamp_label)
preamp_layout.addWidget(self.preamp_slider)
preamp_group.setLayout(preamp_layout)
main_layout.addWidget(preamp_group)
bands_group = QGroupBox("Frequency Bands")
bands_layout = QGridLayout()
for i in range(self.band_count):
freq = self.media_player.get_band_frequency(i)
if freq >= 1000:
freq_text = f"{freq/1000:.1f}k"
else:
freq_text = f"{int(freq)}"
slider_container = QWidget()
slider_layout = QVBoxLayout(slider_container)
slider_layout.setSpacing(2)
slider_layout.setContentsMargins(0, 0, 0, 0)
amp_label = QLabel("0.0")
amp_label.setAlignment(Qt.AlignCenter)
amp_label.setStyleSheet("font-size: 10px;")
slider_layout.addWidget(amp_label)
self.band_labels.append(amp_label)
slider = QSlider(Qt.Vertical)
slider.setRange(-200, 200)
slider.setValue(0)
slider.setTickPosition(QSlider.TicksLeft)
slider.setTickInterval(50)
slider.valueChanged.connect(lambda val, idx=i: self.on_band_changed(idx, val))
slider_layout.addWidget(slider)
self.band_sliders.append(slider)
freq_label = QLabel(freq_text)
freq_label.setAlignment(Qt.AlignCenter)
freq_label.setStyleSheet("font-size: 10px;")
slider_layout.addWidget(freq_label)
bands_layout.addWidget(slider_container, 0, i)
bands_group.setLayout(bands_layout)
main_layout.addWidget(bands_group)
reset_button = QPushButton("Reset to Flat")
reset_button.clicked.connect(self.reset_equalizer)
main_layout.addWidget(reset_button)
def load_current_settings(self):
self.enable_checkbox.setChecked(self.media_player.is_equalizer_enabled())
preamp = self.media_player.get_preamp()
self.preamp_slider.setValue(int(preamp * 10))
self.preamp_label.setText(f"{preamp:.1f} dB")
for i in range(self.band_count):
amp = self.media_player.get_band_amp(i)
self.band_sliders[i].setValue(int(amp * 10))
self.band_labels[i].setText(f"{amp:.1f}")
def _save_settings(self):
if self.parent():
self.parent().save_equalizer_settings()
def _schedule_save(self):
self.save_timer.stop()
self.save_timer.start()
def on_enable_changed(self, state):
enabled = state == Qt.Checked
self.media_player.enable_equalizer(enabled)
self.preset_combo.setEnabled(enabled)
self.preamp_slider.setEnabled(enabled)
for slider in self.band_sliders:
slider.setEnabled(enabled)
self._schedule_save()
def on_preamp_changed(self, value):
amp = value / 10.0
self.preamp_label.setText(f"{amp:.1f} dB")
self.media_player.set_preamp(amp)
self.preset_combo.setCurrentText("Custom")
self._schedule_save()
def on_band_changed(self, band_index, value):
amp = value / 10.0
self.band_labels[band_index].setText(f"{amp:.1f}")
self.media_player.set_band_amp(band_index, amp)
self.preset_combo.setCurrentText("Custom")
self._schedule_save()
def on_preset_changed(self, preset_name):
if preset_name == "Custom":
return
presets = {
"Flat": [0.0] * self.band_count,
"Rock": [8.0, 4.8, -5.6, -8.0, -3.2, 4.0, 8.8, 11.2, 11.2, 11.2],
"Pop": [-1.6, 4.8, 7.2, 8.0, 5.6, 0.0, -2.4, -2.4, -1.6, -1.6],
"Jazz": [0.0, 0.0, 0.0, 2.4, 4.0, 4.0, 0.0, 1.6, 4.0, 5.6],
"Classical": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -7.2, -7.2, -7.2, -9.6],
"Bass Boost": [9.6, 7.2, 5.6, 3.2, 1.6, 0.0, 0.0, 0.0, 0.0, 0.0],
"Treble Boost": [0.0, 0.0, 0.0, 0.0, 0.0, 1.6, 3.2, 5.6, 7.2, 9.6],
}
if preset_name in presets:
values = presets[preset_name]
if len(values) < self.band_count:
values.extend([0.0] * (self.band_count - len(values)))
for slider in self.band_sliders:
slider.blockSignals(True)
self.preamp_slider.blockSignals(True)
for i in range(self.band_count):
amp = values[i]
self.band_sliders[i].setValue(int(amp * 10))
self.band_labels[i].setText(f"{amp:.1f}")
self.media_player.set_band_amp(i, amp)
self.preamp_slider.setValue(0)
self.media_player.set_preamp(0.0)
for slider in self.band_sliders:
slider.blockSignals(False)
self.preamp_slider.blockSignals(False)
self._schedule_save()
def reset_equalizer(self):
self.preset_combo.setCurrentText("Flat")
self.on_preset_changed("Flat")
class MusicPlayer(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Amp")
self.setWindowIcon(load_icon('amp.png'))
self.setGeometry(100, 100, 1000, 600)
self.always_on_top = False
loadStyle()
self.setWindowIcon(self.get_app_icon())
self.init_ui()
self.mediaPlayer = VLCMediaPlayer(self)
self.mediaPlayer.set_volume(100)
self.current_index = 0
app_context = {"main_window": self}
self.plugins = load_plugins(app_context)
self.loop_mode = 0
self.shuffle = False
self.folderAudioFiles = []
self.trackMetadata = {}
self.playback_queue = []
self.setup_dock()
self.setup_main_ui()
self.setup_actions()
self.setup_connections()
self.updatePlaybackMode()
self.setStatusBar(QStatusBar(self))
self.statusBar().showMessage("Ready")
self.timer = QTimer(self)
self.timer.setInterval(1000)
self.timer.timeout.connect(self.update_position)
self.timer.start()
self.settings = QSettings("Raven", "Amp")
self.setup_view_menu()
self.trayIcon = None
self.update_slider = True
self.equalizer_dialog = None
self.load_equalizer_settings()
def init_ui(self):
main_widget = QWidget(self)
self.setCentralWidget(main_widget)
self.main_layout = QVBoxLayout(main_widget)
def setup_view_menu(self):
menu_bar = self.menuBar()
view_menu = menu_bar.addMenu("View")
minimize_action = QAction("Minimize to Tray", self)
minimize_action.triggered.connect(self.minimize_to_tray)
view_menu.addAction(minimize_action)
self.minimizeOnCloseAction = QAction("Closing Window Minimizes to Tray", self, checkable=True)
self.minimizeOnCloseAction.setChecked(self.settings.value("closeToTray", False, type=bool))
self.minimizeOnCloseAction.toggled.connect(lambda checked: self.settings.setValue("closeToTray", checked))
view_menu.addAction(self.minimizeOnCloseAction)
view_menu.addSeparator()
show_queue_action = QAction("Show Queue", self, checkable=True)
show_queue_action.setChecked(False)
show_queue_action.toggled.connect(self.toggle_queue_panel)
view_menu.addAction(show_queue_action)
view_menu.addSeparator()
equalizer_action = QAction("Equalizer...", self)
equalizer_action.triggered.connect(self.show_equalizer)
view_menu.addAction(equalizer_action)
def toggle_queue_panel(self, checked):
if checked:
self.queueDock.show()
else:
self.queueDock.hide()
def show_equalizer(self):
if self.equalizer_dialog is None:
self.equalizer_dialog = EqualizerDialog(self.mediaPlayer, self)
self.equalizer_dialog.show()
self.equalizer_dialog.raise_()
self.equalizer_dialog.activateWindow()
def load_equalizer_settings(self):
enabled = self.settings.value("equalizer/enabled", False, type=bool)
if enabled:
self.mediaPlayer.create_equalizer()
self.mediaPlayer.enable_equalizer(True)
preamp = self.settings.value("equalizer/preamp", 0.0, type=float)
self.mediaPlayer.set_preamp(preamp)
band_count = self.mediaPlayer.get_band_count()
for i in range(band_count):
amp = self.settings.value(f"equalizer/band_{i}", 0.0, type=float)
self.mediaPlayer.set_band_amp(i, amp)
def save_equalizer_settings(self):
self.settings.setValue("equalizer/enabled", self.mediaPlayer.is_equalizer_enabled())
self.settings.setValue("equalizer/preamp", self.mediaPlayer.get_preamp())
band_count = self.mediaPlayer.get_band_count()
for i in range(band_count):
self.settings.setValue(f"equalizer/band_{i}", self.mediaPlayer.get_band_amp(i))
def create_tray_icon(self):
media_path = self.get_media_folder_path()
tray_icon_path = os.path.join(media_path, 'tray.png')
if not os.path.exists(tray_icon_path):
print(f"Tray icon file not found: {tray_icon_path}")
title, artist, album = "Amp", None, None
if self.folderAudioFiles and 0 <= self.current_index < len(self.folderAudioFiles):
current_file = self.folderAudioFiles[self.current_index]
meta = self.extractMetadata(current_file)
title = meta.get('title') or os.path.basename(current_file)
artist = meta.get('artist') or None
album = meta.get('album') or None
self.trayIcon = QSystemTrayIcon(QIcon(tray_icon_path), self)
self.trayMenu = QMenu()
self.trayPlayPauseAction = QAction("Play/Pause", self)
self.trayPlayPauseAction.triggered.connect(self.play_pause)
self.trayMenu.addAction(self.trayPlayPauseAction)
self.trayNextAction = QAction("Next", self)
self.trayNextAction.triggered.connect(self.next_track)
self.trayMenu.addAction(self.trayNextAction)
self.trayPreviousAction = QAction("Previous", self)
self.trayPreviousAction.triggered.connect(self.previous_track)
self.trayMenu.addAction(self.trayPreviousAction)
self.trayShuffleAction = QAction("Shuffle", self)
self.trayShuffleAction.triggered.connect(self.toggle_shuffle)
self.trayMenu.addAction(self.trayShuffleAction)
self.trayLoopAction = QAction("Loop", self)
self.trayLoopAction.triggered.connect(self.toggle_loop)
self.trayMenu.addAction(self.trayLoopAction)
self.trayMenu.addSeparator()
self.trayExitAction = QAction("Exit", self)
self.trayExitAction.triggered.connect(self.close)
self.trayMenu.addAction(self.trayExitAction)
self.trayIcon.setContextMenu(self.trayMenu)
tooltipStr = (f"{artist} - " if artist else "") + title + (f"\n{album}" if album else "")
self.trayIcon.setToolTip(tooltipStr)
self.trayIcon.activated.connect(self.on_tray_icon_activated)
self.trayIcon.show()
def minimize_to_tray(self):
if self.trayIcon is None:
self.create_tray_icon()
self.hide()
self.trayIcon.showMessage("Amp", "Amp minimized to tray", QSystemTrayIcon.Information, 2000)
def on_tray_icon_activated(self, reason):
if reason == QSystemTrayIcon.Trigger:
self.showNormal()
self.activateWindow()
self.trayIcon.hide()
self.trayIcon.deleteLater()
self.trayIcon = None
def closeEvent(self, event):
if self.minimizeOnCloseAction.isChecked():
if self.trayIcon is None:
event.ignore()
self.minimize_to_tray()
else:
event.accept()
else:
event.accept()
def get_app_icon(self):
media_path = self.get_media_folder_path()
icon_path = os.path.join(media_path, 'amp.png')
if os.path.exists(icon_path):
return QIcon(icon_path)
else:
print(f"Icon file not found: {icon_path}")
return QIcon()
def get_media_folder_path(self):
if getattr(sys, 'frozen', False):
base_path = sys._MEIPASS
else:
base_path = os.path.dirname(__file__)
return os.path.join(base_path, 'media')
def handle_media_ended(self):
if self.playback_queue:
next_file = self.playback_queue.pop(0)
self.update_queue_display()
current_volume = self.volumeSlider.value()
self.mediaPlayer.set_media(next_file)
self.mediaPlayer.play()
self.mediaPlayer.set_volume(current_volume)
try:
idx = self.folderAudioFiles.index(next_file)
self.current_index = idx
except ValueError:
idx = len(self.folderAudioFiles)
self.folderAudioFiles.append(next_file)
self.current_index = idx
meta = self.extractMetadata(next_file)
self.trackMetadata[idx] = meta
self.updateTrackInfo()
return
if self.loop_mode == 2:
current_volume = self.volumeSlider.value()
self.mediaPlayer.set_media(self.folderAudioFiles[self.current_index])
self.mediaPlayer.play()
self.mediaPlayer.set_volume(current_volume)
elif self.shuffle:
import random
self.current_index = random.randint(0, len(self.folderAudioFiles) - 1)
current_volume = self.volumeSlider.value()
self.mediaPlayer.set_media(self.folderAudioFiles[self.current_index])
self.mediaPlayer.play()
self.mediaPlayer.set_volume(current_volume)
else:
self.current_index += 1
if self.current_index >= len(self.folderAudioFiles):
if self.loop_mode == 1:
self.current_index = 0
else:
self.current_index -= 1
self.mediaPlayer.stop()
self.playButton.setIcon(self.play_icon)
return
current_volume = self.volumeSlider.value()
self.mediaPlayer.set_media(self.folderAudioFiles[self.current_index])
self.mediaPlayer.play()
self.mediaPlayer.set_volume(current_volume)
self.updateTrackInfo()
def extractMetadata(self, file_path):
if MutagenFile is None:
return {
'title': None,
'artist': None,
'album': None,
'year': None,
'artwork': None,
'track': None
}
try:
audio = MutagenFile(file_path)
if not audio or not audio.tags:
return {
'title': None,
'artist': None,
'album': None,
'year': None,
'artwork': None,
'track': None
}
title, artist, album, year, artwork_data, track = None, None, None, None, None, None
if file_path.lower().endswith('.m4a'):
title = audio.tags.get("©nam", [None])[0]
artist = audio.tags.get("©ART", [None])[0]
album = audio.tags.get("©alb", [None])[0]
year = audio.tags.get("©day", [None])[0]
track_info = audio.tags.get("trkn", [(None, None)])[0]
track = track_info[0] if track_info else None
if "covr" in audio.tags:
for cover in audio.tags["covr"]:
artwork_data = cover
elif file_path.lower().endswith('.flac'):
title = audio.get('title', [None])[0] if 'title' in audio else None
artist = audio.get('artist', [None])[0] if 'artist' in audio else None
album = audio.get('album', [None])[0] if 'album' in audio else None
year = audio.get('date', [None])[0] if 'date' in audio else None
track = audio.get('tracknumber', [None])[0] if 'tracknumber' in audio else None
pics = getattr(audio, "pictures", [])
if pics:
artwork_data = pics[0].data
elif file_path.lower().endswith('.ogg'):
for tag in audio.tags.keys():
if tag == "title":
title = audio.tags[tag][0]
elif tag == "artist":
artist = audio.tags[tag][0]
elif tag == "album":
album = audio.tags[tag][0]
elif tag == "date":
year = audio.tags[tag][0]
elif tag == "metadata_block_picture":
from mutagen.flac import Picture
import base64
data = base64.b64decode(audio.tags[tag][0])
picture = Picture(data)
artwork_data = picture.data
elif tag == "tracknumber":
track = audio.tags[tag][0]
else:
if 'TIT2' in audio.tags:
title = str(audio.tags['TIT2'].text[0]) if audio.tags['TIT2'].text else None
if 'TPE1' in audio.tags:
artist = str(audio.tags['TPE1'].text[0]) if audio.tags['TPE1'].text else None
if 'TALB' in audio.tags:
album = str(audio.tags['TALB'].text[0]) if audio.tags['TALB'].text else None
if 'TDRC' in audio.tags:
year = str(audio.tags['TDRC'].text[0]) if audio.tags['TDRC'].text else None
elif 'TYER' in audio.tags:
year = str(audio.tags['TYER'].text[0]) if audio.tags['TYER'].text else None
if 'TRCK' in audio.tags:
try:
track_str = str(audio.tags['TRCK'].text[0]) if audio.tags['TRCK'].text else None
if track_str:
track = track_str.split('/')[0].strip()
except Exception:
track = None
for tag in audio.tags.values():
if tag.__class__.__name__ == 'APIC':
artwork_data = tag.data
break
return {
'title': title,
'artist': artist,
'album': album,
'year': year,
'artwork': artwork_data,
'track': track
}
except Exception:
return {
'title': None,
'artist': None,
'album': None,
'year': None,
'artwork': None,
'track': None
}
def updateTrackInfo(self):
if not self.folderAudioFiles or self.current_index >= len(self.folderAudioFiles):
return
current_file = self.folderAudioFiles[self.current_index]
meta = self.extractMetadata(current_file)
self.trackMetadata[self.current_index] = meta
title = meta.get('title') or os.path.basename(current_file)
artist = meta.get('artist') or "Unknown Artist"
album = meta.get('album') or "Unknown Album"
year = meta.get('year') or ""
artwork_data = meta.get('artwork')
self.titleLabel.setText(title)
self.authorLabel.setText(artist)
self.albumLabel.setText(album)
self.yearLabel.setText(year)
if artwork_data:
pixmap = QPixmap()
pixmap.loadFromData(artwork_data)
pixmap = pixmap.scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.artLabel.setPixmap(pixmap)
else:
media_path = self.get_media_folder_path()
placeholder_path = os.path.join(media_path, "albumartplaceholder.png")
if os.path.exists(placeholder_path):
pixmap = QPixmap(placeholder_path).scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.artLabel.setPixmap(pixmap)
else:
self.artLabel.setText("No Art")
self.artLabel.setStyleSheet("border: 1px solid #999; color: gray;")
self.update_status_bar()
if self.trayIcon:
tooltipStr = (f"{artist} - " if artist else "") + title + (f"\nAlbum: {album}" if album else "")
self.trayIcon.setToolTip(tooltipStr)
def resetTrackInfo(self):
self.titleLabel.setText("Select a song to begin")
self.authorLabel.setText("")
self.albumLabel.setText("")
self.yearLabel.setText("")
media_path = self.get_media_folder_path()
placeholder_path = os.path.join(media_path, "albumartplaceholder.png")
if os.path.exists(placeholder_path):
pm = QPixmap(placeholder_path).scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.artLabel.setPixmap(pm)
else:
self.artLabel.setText("No Art")
self.artLabel.setStyleSheet("border: 1px solid #999; color: gray;")
self.timeElapsedLabel.setText("0:00")
self.timeRemainingLabel.setText("0:00")
self.positionSlider.setRange(0, 0)
self.positionSlider.setValue(0)
if self.statusBar():
self.statusBar().showMessage("Select a song to begin")
if self.trayIcon:
self.trayIcon.setToolTip("Amp")
def setup_dock(self):
self.fileDock = QDockWidget("File Explorer", self)
self.fileDock.setObjectName("FileExplorerDock")
self.fileDock.setFeatures(QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable)
self.fileModel = QFileSystemModel()
self.fileModel.setReadOnly(True)
self.fileTreeView = QTreeView()
self.fileTreeView.setModel(self.fileModel)
self.fileTreeView.setContextMenuPolicy(Qt.CustomContextMenu)
self.fileTreeView.customContextMenuRequested.connect(self.show_file_context_menu)
self.fileDock.setWidget(self.fileTreeView)
self.addDockWidget(Qt.LeftDockWidgetArea, self.fileDock)
self.fileDock.hide()
self.queueDock = QDockWidget("Queue", self)
self.queueDock.setObjectName("QueueDock")
self.queueDock.setFeatures(QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable)
self.queueListWidget = QListWidget()
self.queueListWidget.setContextMenuPolicy(Qt.CustomContextMenu)
self.queueListWidget.customContextMenuRequested.connect(self.show_queue_context_menu)
self.queueListWidget.doubleClicked.connect(self.play_from_queue)
self.queueDock.setWidget(self.queueListWidget)
self.addDockWidget(Qt.RightDockWidgetArea, self.queueDock)
self.queueDock.hide()
def setup_main_ui(self):
media_path = self.get_media_folder_path()
top_container = QWidget()
top_layout = QHBoxLayout(top_container)
top_layout.setContentsMargins(10, 10, 10, 10)
top_layout.setSpacing(15)
self.artLabel = QLabel()
self.artLabel.setFixedSize(200, 200)
self.artLabel.setAlignment(Qt.AlignCenter)
placeholder_path = os.path.join(media_path, "albumartplaceholder.png")
if os.path.exists(placeholder_path):
pm = QPixmap(placeholder_path).scaled(200, 200, Qt.KeepAspectRatio, Qt.SmoothTransformation)
self.artLabel.setPixmap(pm)
else:
self.artLabel.setText("No Art")
self.artLabel.setStyleSheet("border: 1px solid #999; color: gray;")
top_layout.addWidget(self.artLabel, alignment=Qt.AlignTop)
info_layout = QVBoxLayout()
info_layout.setSpacing(5)
self.titleLabel = QLabel("Select a song to begin")
self.titleLabel.setStyleSheet("font-size: 16px; font-weight: bold;")
self.titleLabel.setWordWrap(False)
info_layout.addWidget(self.titleLabel)
self.authorLabel = QLabel("")
self.authorLabel.setStyleSheet("font-size: 13px;")
self.authorLabel.setWordWrap(False)
info_layout.addWidget(self.authorLabel)
self.albumLabel = QLabel("")
self.albumLabel.setStyleSheet("font-size: 13px;")
self.albumLabel.setWordWrap(False)
info_layout.addWidget(self.albumLabel)
self.yearLabel = QLabel("")
self.yearLabel.setStyleSheet("font-size: 13px;")
self.yearLabel.setWordWrap(False)
info_layout.addWidget(self.yearLabel)
info_layout.addStretch(1)
top_layout.addLayout(info_layout)
self.main_layout.addWidget(top_container)
bottom_container = QWidget()
bottom_layout = QVBoxLayout(bottom_container)
bottom_layout.setContentsMargins(5, 5, 5, 5)
controls_layout = QHBoxLayout()
controls_layout.setSpacing(15)
controls_layout.setContentsMargins(0, 0, 0, 0)
media_controls_widget = QWidget()
media_controls_layout = QHBoxLayout(media_controls_widget)
media_controls_layout.setSpacing(15)
media_controls_layout.setContentsMargins(0, 0, 0, 0)
self.shuffleButton = QPushButton("Off")
self.shuffleButton.setIcon(QIcon(os.path.join(media_path, "shuffle.png")))
media_controls_layout.addWidget(self.shuffleButton)
self.prevButton = QPushButton()
self.prevButton.setIcon(QIcon(os.path.join(media_path, "prev.png")))
self.prevButton.setToolTip("Previous")
media_controls_layout.addWidget(self.prevButton)
self.playButton = QPushButton()
self.play_icon = QIcon(os.path.join(media_path, "play.png"))
self.pause_icon = QIcon(os.path.join(media_path, "pause.png"))
self.playButton.setIcon(self.play_icon)
self.playButton.setToolTip("Play/Pause")
media_controls_layout.addWidget(self.playButton)
self.nextButton = QPushButton()
self.nextButton.setIcon(QIcon(os.path.join(media_path, "next.png")))
self.nextButton.setToolTip("Next")
media_controls_layout.addWidget(self.nextButton)
self.loopButton = QPushButton("Off")
self.loopButton.setToolTip("Loop")
self.loopButton.setIcon(QIcon(os.path.join(media_path, "loop.png")))
media_controls_layout.addWidget(self.loopButton)
media_controls_layout.setAlignment(Qt.AlignCenter)
controls_layout.addWidget(media_controls_widget, stretch=1, alignment=Qt.AlignCenter)
volume_icon = QIcon(os.path.join(media_path, "volume.png"))
self.volumeLabel = QLabel()
self.volumeLabel.setPixmap(volume_icon.pixmap(24, 24))
self.volumeSlider = QSlider(Qt.Horizontal)
self.volumeSlider.setRange(0, 100)
self.volumeSlider.setValue(100)
controls_layout.addWidget(self.volumeLabel, alignment=Qt.AlignRight)
controls_layout.addWidget(self.volumeSlider, alignment=Qt.AlignRight)
bottom_layout.addLayout(controls_layout)
progress_layout = QHBoxLayout()
progress_layout.setSpacing(10)
self.timeElapsedLabel = QLabel("0:00")
self.positionSlider = QSlider(Qt.Horizontal)
self.positionSlider.setObjectName("progressBar")
self.positionSlider.setRange(0, 0)
self.timeRemainingLabel = QLabel("0:00")
progress_layout.addWidget(self.timeElapsedLabel)
progress_layout.addWidget(self.positionSlider, stretch=1)
progress_layout.addWidget(self.timeRemainingLabel)
bottom_layout.addLayout(progress_layout)
self.main_layout.addWidget(bottom_container)
def setup_actions(self):
menu_bar = self.menuBar()
file_menu = menu_bar.addMenu("File")
openFileAction = QAction("Open File...", self)
openFileAction.triggered.connect(self.open_file)
file_menu.addAction(openFileAction)
openFolderAction = QAction("Open Folder...", self)
openFolderAction.triggered.connect(self.open_folder)
file_menu.addAction(openFolderAction)
file_menu.addSeparator()
exitAction = QAction("Exit", self)
exitAction.triggered.connect(self.close)
file_menu.addAction(exitAction)
def setup_connections(self):
if self.mediaPlayer:
self.mediaPlayer.positionChanged.connect(self.on_position_changed)
self.mediaPlayer.durationChanged.connect(self.on_duration_changed)
self.mediaPlayer.mediaEnded.connect(self.handle_media_ended)
self.playButton.clicked.connect(self.play_pause)
self.prevButton.clicked.connect(self.previous_track)
self.nextButton.clicked.connect(self.next_track)
self.shuffleButton.clicked.connect(self.toggle_shuffle)
self.loopButton.clicked.connect(self.toggle_loop)
self.fileTreeView.doubleClicked.connect(self.onFileTreeDoubleClicked)
if self.mediaPlayer:
self.volumeSlider.valueChanged.connect(self.mediaPlayer.set_volume)
self.positionSlider.sliderPressed.connect(lambda: self.allow_position_updates(False))
self.positionSlider.sliderReleased.connect(self.on_slider_released)
def allow_position_updates(self, allow: bool = True):
self.update_slider = allow
def on_slider_released(self):
self.seek(self.positionSlider.value())
self.allow_position_updates(True)
def open_folder(self):
folder = QFileDialog.getExistingDirectory(self, "Open Folder with Audio Files")
if folder:
self.fileDock.show()
self.fileModel.setRootPath(folder)
self.fileModel.sort(0, Qt.AscendingOrder)
self.fileTreeView.setRootIndex(self.fileModel.index(folder))
self.statusBar().showMessage(f"Opened folder: {folder}", 3000)
self.folderAudioFiles.clear()
self.trackMetadata.clear()
audio_extensions = ('.mp3', '.wav', '.ogg', '.flac', '.m4a')
try:
all_entries = os.listdir(folder)
except OSError as e:
self.statusBar().showMessage(f"Error reading folder: {e}", 5000)
return
files_with_path = []
for name in all_entries:
if name.lower().endswith(audio_extensions):
full_path = os.path.join(folder, name)
try:
os.stat(full_path)
except OSError:
# Skip entries that cannot be read/stat'ed
continue
files_with_path.append(full_path)
all_have_track = True
track_info = {}
for full_path in files_with_path:
meta = self.extractMetadata(full_path)
track = meta.get('track')
if track is None or track == "":
all_have_track = False
break
try:
track_num = int(track)
except ValueError:
all_have_track = False
break
track_info[full_path] = track_num
if all_have_track:
sorted_files = sorted(files_with_path, key=lambda fp: track_info[fp])
else:
sorted_files = sorted(files_with_path)
self.folderAudioFiles = sorted_files
if self.folderAudioFiles and self.mediaPlayer:
self.current_index = 0
self.mediaPlayer.set_media(self.folderAudioFiles[0])
self.updateTrackInfo()
else:
if self.mediaPlayer:
self.mediaPlayer.stop()
self.playButton.setIcon(self.play_icon)
self.resetTrackInfo()
def onFileTreeDoubleClicked(self, index: QModelIndex):
file_path = self.fileModel.filePath(index)
if os.path.isfile(file_path) and file_path.lower().endswith(('.mp3', '.wav', '.ogg', '.flac', '.m4a')):
try:
idx = self.folderAudioFiles.index(file_path)
except ValueError:
idx = len(self.folderAudioFiles)
self.folderAudioFiles.append(file_path)
self.current_index = idx
if self.mediaPlayer:
current_volume = self.volumeSlider.value()
self.mediaPlayer.set_media(file_path)
self.mediaPlayer.play()
self.mediaPlayer.set_volume(current_volume)
self.playButton.setIcon(self.pause_icon)
meta = self.extractMetadata(file_path)
self.trackMetadata[idx] = meta