吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 3291|回复: 55
收起左侧

[Python 原创] 5-18更新,全AI写的音乐播放器来了,大家拿去魔改玩吧(能下歌词及封面啦啦啦)。。

  [复制链接]
liuyang207 发表于 2025-4-30 16:22
本帖最后由 liuyang207 于 2025-5-19 20:41 编辑

2025-5-18 更新。
@top777  首先感谢top777的下载歌词及封面的代码,让这个播放Mp3的小软件有了质的飞越。
现在软件启动时会自动下载播放列表中歌曲的歌词及封面并内嵌(如有则跳过),所以,你可能放着放着就发现歌曲有歌词和封面了(第一次启动时因为还没有添加歌曲列表,添加后播放列表中右键手动下载)。



--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------一直想做一个界面好看点的音乐播放器,今天在GPT-4.1的神功下,小半天的时间总算搞好了。有旋转的黑胶唱片封面、浮动的歌词显示。(程序读取歌曲内嵌的封面和歌词及目录下同名LRC。)
全AI写的,我没有写一句程序,大家可以随意魔改自己想要的功能。
目录里有编译好的EXE文件,也有源码。https://www.alipan.com/s/w2eqoL2fZbw
                                                                       https://pan.baidu.com/s/1hj6i3hBpidwD7NXy2GMh0Q?pwd=uky8    提取码: uky8
----------------------------------------------------------------------------------------------------------------------






[Python] 纯文本查看 复制代码
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012
0013
0014
0015
0016
0017
0018
0019
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032
0033
0034
0035
0036
0037
0038
0039
0040
0041
0042
0043
0044
0045
0046
0047
0048
0049
0050
0051
0052
0053
0054
0055
0056
0057
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073
0074
0075
0076
0077
0078
0079
0080
0081
0082
0083
0084
0085
0086
0087
0088
0089
0090
0091
0092
0093
0094
0095
0096
0097
0098
0099
0100
0101
0102
0103
0104
0105
0106
0107
0108
0109
0110
0111
0112
0113
0114
0115
0116
0117
0118
0119
0120
0121
0122
0123
0124
0125
0126
0127
0128
0129
0130
0131
0132
0133
0134
0135
0136
0137
0138
0139
0140
0141
0142
0143
0144
0145
0146
0147
0148
0149
0150
0151
0152
0153
0154
0155
0156
0157
0158
0159
0160
0161
0162
0163
0164
0165
0166
0167
0168
0169
0170
0171
0172
0173
0174
0175
0176
0177
0178
0179
0180
0181
0182
0183
0184
0185
0186
0187
0188
0189
0190
0191
0192
0193
0194
0195
0196
0197
0198
0199
0200
0201
0202
0203
0204
0205
0206
0207
0208
0209
0210
0211
0212
0213
0214
0215
0216
0217
0218
0219
0220
0221
0222
0223
0224
0225
0226
0227
0228
0229
0230
0231
0232
0233
0234
0235
0236
0237
0238
0239
0240
0241
0242
0243
0244
0245
0246
0247
0248
0249
0250
0251
0252
0253
0254
0255
0256
0257
0258
0259
0260
0261
0262
0263
0264
0265
0266
0267
0268
0269
0270
0271
0272
0273
0274
0275
0276
0277
0278
0279
0280
0281
0282
0283
0284
0285
0286
0287
0288
0289
0290
0291
0292
0293
0294
0295
0296
0297
0298
0299
0300
0301
0302
0303
0304
0305
0306
0307
0308
0309
0310
0311
0312
0313
0314
0315
0316
0317
0318
0319
0320
0321
0322
0323
0324
0325
0326
0327
0328
0329
0330
0331
0332
0333
0334
0335
0336
0337
0338
0339
0340
0341
0342
0343
0344
0345
0346
0347
0348
0349
0350
0351
0352
0353
0354
0355
0356
0357
0358
0359
0360
0361
0362
0363
0364
0365
0366
0367
0368
0369
0370
0371
0372
0373
0374
0375
0376
0377
0378
0379
0380
0381
0382
0383
0384
0385
0386
0387
0388
0389
0390
0391
0392
0393
0394
0395
0396
0397
0398
0399
0400
0401
0402
0403
0404
0405
0406
0407
0408
0409
0410
0411
0412
0413
0414
0415
0416
0417
0418
0419
0420
0421
0422
0423
0424
0425
0426
0427
0428
0429
0430
0431
0432
0433
0434
0435
0436
0437
0438
0439
0440
0441
0442
0443
0444
0445
0446
0447
0448
0449
0450
0451
0452
0453
0454
0455
0456
0457
0458
0459
0460
0461
0462
0463
0464
0465
0466
0467
0468
0469
0470
0471
0472
0473
0474
0475
0476
0477
0478
0479
0480
0481
0482
0483
0484
0485
0486
0487
0488
0489
0490
0491
0492
0493
0494
0495
0496
0497
0498
0499
0500
0501
0502
0503
0504
0505
0506
0507
0508
0509
0510
0511
0512
0513
0514
0515
0516
0517
0518
0519
0520
0521
0522
0523
0524
0525
0526
0527
0528
0529
0530
0531
0532
0533
0534
0535
0536
0537
0538
0539
0540
0541
0542
0543
0544
0545
0546
0547
0548
0549
0550
0551
0552
0553
0554
0555
0556
0557
0558
0559
0560
0561
0562
0563
0564
0565
0566
0567
0568
0569
0570
0571
0572
0573
0574
0575
0576
0577
0578
0579
0580
0581
0582
0583
0584
0585
0586
0587
0588
0589
0590
0591
0592
0593
0594
0595
0596
0597
0598
0599
0600
0601
0602
0603
0604
0605
0606
0607
0608
0609
0610
0611
0612
0613
0614
0615
0616
0617
0618
0619
0620
0621
0622
0623
0624
0625
0626
0627
0628
0629
0630
0631
0632
0633
0634
0635
0636
0637
0638
0639
0640
0641
0642
0643
0644
0645
0646
0647
0648
0649
0650
0651
0652
0653
0654
0655
0656
0657
0658
0659
0660
0661
0662
0663
0664
0665
0666
0667
0668
0669
0670
0671
0672
0673
0674
0675
0676
0677
0678
0679
0680
0681
0682
0683
0684
0685
0686
0687
0688
0689
0690
0691
0692
0693
0694
0695
0696
0697
0698
0699
0700
0701
0702
0703
0704
0705
0706
0707
0708
0709
0710
0711
0712
0713
0714
0715
0716
0717
0718
0719
0720
0721
0722
0723
0724
0725
0726
0727
0728
0729
0730
0731
0732
0733
0734
0735
0736
0737
0738
0739
0740
0741
0742
0743
0744
0745
0746
0747
0748
0749
0750
0751
0752
0753
0754
0755
0756
0757
0758
0759
0760
0761
0762
0763
0764
0765
0766
0767
0768
0769
0770
0771
0772
0773
0774
0775
0776
0777
0778
0779
0780
0781
0782
0783
0784
0785
0786
0787
0788
0789
0790
0791
0792
0793
0794
0795
0796
0797
0798
0799
0800
0801
0802
0803
0804
0805
0806
0807
0808
0809
0810
0811
0812
0813
0814
0815
0816
0817
0818
0819
0820
0821
0822
0823
0824
0825
0826
0827
0828
0829
0830
0831
0832
0833
0834
0835
0836
0837
0838
0839
0840
0841
0842
0843
0844
0845
0846
0847
0848
0849
0850
0851
0852
0853
0854
0855
0856
0857
0858
0859
0860
0861
0862
0863
0864
0865
0866
0867
0868
0869
0870
0871
0872
0873
0874
0875
0876
0877
0878
0879
0880
0881
0882
0883
0884
0885
0886
0887
0888
0889
0890
0891
0892
0893
0894
0895
0896
0897
0898
0899
0900
0901
0902
0903
0904
0905
0906
0907
0908
0909
0910
0911
0912
0913
0914
0915
0916
0917
0918
0919
0920
0921
0922
0923
0924
0925
0926
0927
0928
0929
0930
0931
0932
0933
0934
0935
0936
0937
0938
0939
0940
0941
0942
0943
0944
0945
0946
0947
0948
0949
0950
0951
0952
0953
0954
0955
0956
0957
0958
0959
0960
0961
0962
0963
0964
0965
0966
0967
0968
0969
0970
0971
0972
0973
0974
0975
0976
0977
0978
0979
0980
0981
0982
0983
0984
0985
0986
0987
0988
0989
0990
0991
0992
0993
0994
0995
0996
0997
0998
0999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QWidget, QLabel, QPushButton, QSlider, QHBoxLayout, QVBoxLayout, QGridLayout, QFileDialog, QListWidget, QListWidgetItem, QMenu
)
from PyQt5.QtCore import Qt, QTimer, QUrl, QByteArray, pyqtSignal
from PyQt5.QtGui import QPixmap, QPainter, QTransform, QPainterPath, QFont, QColor, QLinearGradient, QBrush, QPen, QCursor
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC
from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent
import vlc
import re
 
def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)
 
# 旋转封面控件
class RotatingCover(QLabel):
    def __init__(self, song_path, default_cover="fm.png"):
        super().__init__()
        self.angle = 0
        self.pixmap = self.load_cover(song_path, default_cover)
        if self.pixmap.isNull():
            self.setText("未找到封面")
            self.setStyleSheet("color: #fff; background: #666; border-radius: 125px; font-size: 20px;")
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.rotate)
        self.timer.start(50# 旋转速度
 
    def load_cover(self, song_path, default_cover):
        # 1. 尝试同名jpg
        base, _ = os.path.splitext(song_path)
        jpg_path = base + ".jpg"
        if os.path.exists(jpg_path):
            return QPixmap(jpg_path)
        # 2. 尝试MP3内嵌封面
        try:
            audio = MP3(song_path, ID3=ID3)
            for tag in audio.tags.values():
                if isinstance(tag, APIC):
                    ba = QByteArray(tag.data)
                    pixmap = QPixmap()
                    pixmap.loadFromData(ba)
                    if not pixmap.isNull():
                        return pixmap
        except Exception as e:
            pass
        # 3. 默认封面
        if os.path.exists(default_cover):
            return QPixmap(default_cover)
        return QPixmap()  # 空pixmap
 
    def rotate(self):
        if self.pixmap.isNull():
            return
        self.angle = (self.angle + 2) % 360
        target_size = 250
        # 只旋转封面
        cover_scaled = self.pixmap.scaled(target_size, target_size, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
        cover_rotated = cover_scaled.transformed(QTransform().rotate(self.angle), Qt.SmoothTransformation)
        # 裁剪为圆形
        cover_circle = QPixmap(target_size, target_size)
        cover_circle.fill(Qt.transparent)
        painter = QPainter(cover_circle)
        painter.setRenderHint(QPainter.Antialiasing)
        path = QPainterPath()
        path.addEllipse(0, 0, target_size, target_size)
        painter.setClipPath(path)
        x = (target_size - cover_rotated.width()) // 2
        y = (target_size - cover_rotated.height()) // 2
        painter.drawPixmap(x, y, cover_rotated)
        painter.end()
        self.setPixmap(cover_circle)
 
    def setCover(self, song_path, default_cover="fm.png"):
        self.pixmap = self.load_cover(song_path, default_cover)
 
class CoverWidget(QWidget):
    def __init__(self, default_cover="fm.png"):
        super().__init__()
        self.setFixedSize(250, 250)
        self.bg_pixmap = QPixmap(default_cover) if os.path.exists(default_cover) else QPixmap()
        self.cover_pixmap = QPixmap()
        self.angle = 0
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.rotate)
        self.timer.start(50)
        self.rotate()
        self.default_cover = default_cover
 
    def rotate(self):
        self.angle = (self.angle + 2) % 360
        self.update()
 
    def setCover(self, song_path):
        pixmap = self.load_cover(song_path, self.default_cover)
        self.cover_pixmap = pixmap
        self.update()
 
    def load_cover(self, song_path, default_cover):
        if not song_path or not os.path.exists(song_path):
            return QPixmap(default_cover) if os.path.exists(default_cover) else QPixmap()
        # 1. 尝试同名jpg
        base, _ = os.path.splitext(song_path)
        jpg_path = base + ".jpg"
        if os.path.exists(jpg_path):
            return QPixmap(jpg_path)
        # 2. 尝试MP3内嵌封面
        try:
            audio = MP3(song_path, ID3=ID3)
            for tag in audio.tags.values():
                if isinstance(tag, APIC):
                    ba = QByteArray(tag.data)
                    pixmap = QPixmap()
                    pixmap.loadFromData(ba)
                    if not pixmap.isNull():
                        return pixmap
        except Exception as e:
            pass
        # 3. 默认封面
        if os.path.exists(default_cover):
            return QPixmap(default_cover)
        return QPixmap()  # 空pixmap
 
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
 
        # 1. 画旋转后的 fm.png
        if not self.bg_pixmap.isNull():
            bg = self.bg_pixmap.scaled(250, 250, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            # 以中心为原点旋转
            painter.save()
            painter.translate(self.width() // 2, self.height() // 2)
            painter.rotate(self.angle)
            painter.translate(-bg.width() // 2, -bg.height() // 2)
            painter.drawPixmap(0, 0, bg)
            painter.restore()
 
        # 2. 画旋转后的封面(内切圆,直径130,居中)
        if not self.cover_pixmap.isNull():
            size = 130
            # 1. 先裁剪为正方形
            src = self.cover_pixmap
            w, h = src.width(), src.height()
            if w != h:
                side = min(w, h)
                x = (w - side) // 2
                y = (h - side) // 2
                src = src.copy(x, y, side, side)
            # 2. 缩放
            cover = src.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
            # 3. 裁剪为圆形
            cover_circle = QPixmap(size, size)
            cover_circle.fill(Qt.transparent)
            p = QPainter(cover_circle)
            p.setRenderHint(QPainter.Antialiasing)
            path = QPainterPath()
            path.addEllipse(0, 0, size, size)
            p.setClipPath(path)
            p.drawPixmap(0, 0, cover)
            p.end()
            # 4. 以中心为原点旋转
            painter.save()
            painter.translate(self.width() // 2, self.height() // 2)
            painter.rotate(self.angle)
            painter.translate(-size // 2, -size // 2)
            painter.drawPixmap(0, 0, cover_circle)
            painter.restore()
 
        painter.end()
 
# 动态歌词控件(简化版)
class LyricLabel(QWidget):
    def __init__(self):
        super().__init__()
        self.lyrics = []  # [(time, text), ...]
        self.current_index = 0
        self.setMinimumHeight(120)
        self.setStyleSheet("background: transparent;")
        self.color_main = QColor("#fff")
        self.color_other = QColor("#aaa")
 
    def setDemoText(self, text):
        # 只显示一行小字号的提示
        self.lyrics = []
        self.current_index = 0
        self.demo_text = text
        self.update()
 
    def setLyrics(self, lyrics):
        self.lyrics = lyrics
        self.current_index = 0
        self.demo_text = None
        self.update()
 
    def setCurrentTime(self, cur_time):
        self.cur_time = cur_time  # 记录当前时间
        idx = 0
        for i, (t, _) in enumerate(self.lyrics):
            if cur_time >= t:
                idx = i
            else:
                break
        if idx != self.current_index:
            self.current_index = idx
            self.update()
        else:
            self.update()  # 即使index没变,也要刷新实现平滑
 
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        w, h = self.width(), self.height()
 
        # 计算要显示的歌词行
        lines = []
        for offset in range(-2, 3):
            idx = self.current_index + offset
            if 0 <= idx < len(self.lyrics):
                lines.append((offset, self.lyrics[idx][1]))
        total_lines = len(lines)
        if total_lines == 0:
            # demo_text
            if hasattr(self, "demo_text") and self.demo_text:
                font = QFont("微软雅黑", 13)
                painter.setFont(font)
                painter.setPen(QColor("#aaa"))
                painter.drawText(0, 0, w, h, Qt.AlignHCenter | Qt.AlignVCenter, self.demo_text)
            return
 
        # 1. 先确定最大允许的行高
        max_line_height = h // max(total_lines, 1)
 
        # 2. 计算主行最大字号
        main_text = lines[[o for o, _ in lines].index(0)][1] if any(o == 0 for o, _ in lines) else lines[0][1]
        if not main_text.strip():
            main_text = "啊"  # 占位符,防止空行导致字号过大
        main_font_size = max_line_height
        while main_font_size > 10:
            font_main = QFont("微软雅黑", main_font_size, QFont.Bold)
            painter.setFont(font_main)
            rect = painter.fontMetrics().boundingRect(main_text)
            if rect.width() <= w * 0.95 and rect.height() <= max_line_height * 0.95:
                break
            main_font_size -= 1
        font_main = QFont("微软雅黑", main_font_size, QFont.Bold)
        other_font_size = int(main_font_size * 0.7)
        font_other = QFont("微软雅黑", other_font_size)
        painter.setFont(font_main)
        line_height = max(painter.fontMetrics().height(), int(h / max(total_lines, 1)))
 
        # ====== 平滑滚动核心 ======
        # 当前歌词时间
        cur_time = None
        if hasattr(self, "parent") and hasattr(self.parent(), "vlc_player"):
            cur_time = self.parent().vlc_player.get_time() / 1000
        elif hasattr(self, "cur_time"):
            cur_time = self.cur_time
        else:
            cur_time = 0
 
        # 当前行和下一行的时间
        cur_idx = self.current_index
        cur_line_time = self.lyrics[cur_idx][0] if self.lyrics else 0
        next_line_time = self.lyrics[cur_idx+1][0] if (self.lyrics and cur_idx+1 < len(self.lyrics)) else cur_line_time+2
 
        # 计算当前行到下一行的进度百分比
        if next_line_time > cur_line_time:
            percent = min(max((cur_time - cur_line_time) / (next_line_time - cur_line_time), 0), 1)
        else:
            percent = 0
 
        # 歌词整体Y轴平滑上移
        scroll_offset = -percent * line_height
 
        # 歌词整体垂直居中
        start_y = (h - total_lines * line_height) // 2 + scroll_offset
 
        for i, (offset, text) in enumerate(lines):
            y = start_y + i * line_height + line_height // 2
            if offset == 0:
                painter.setFont(font_main)
                # ====== 彩虹色高亮 ======
                grad = QLinearGradient(0, y-line_height//2, w, y+line_height//2)
                for j in range(7):
                    grad.setColorAt(j/6, QColor.fromHsv(int((j*60 + (cur_time*60)%360)%360), 255, 255))
                painter.setPen(QPen(QBrush(grad), 0))
            else:
                painter.setFont(font_other)
                painter.setPen(self.color_other)
            painter.drawText(0, int(y-line_height//2), w, line_height, Qt.AlignHCenter | Qt.AlignVCenter, text)
 
class PlaylistWidget(QListWidget):
    favSong = pyqtSignal(str)
 
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setStyleSheet("font-size:18px;background:#222;color:#fff;")
        self.setDragDropMode(QListWidget.InternalMove)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_menu)
        self.model().rowsMoved.connect(self.on_rows_moved)
 
    def show_menu(self, pos):
        menu = QMenu(self)
        act_fav = menu.addAction("收藏该歌曲")
        act_del = menu.addAction("删除选中项")
        act_clear = menu.addAction("清空列表")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == act_fav:
            self.fav_selected()
        elif action == act_del:
            self.delete_selected()
        elif action == act_clear:
            self.clear_playlist()
 
    def delete_selected(self):
        for item in self.selectedItems():
            row = self.row(item)
            self.takeItem(row)
            if hasattr(self.parent(), "sync_song_list"):
                self.parent().sync_song_list()
 
    def clear_playlist(self):
        self.clear()
        if hasattr(self.parent(), "sync_song_list"):
            self.parent().sync_song_list()
 
    def on_rows_moved(self, *args):
        if hasattr(self.parent(), "sync_song_list"):
            self.parent().sync_song_list()
 
    def fav_selected(self):
        for item in self.selectedItems():
            song = item.toolTip()
            self.favSong.emit(song)
 
class FloatingLyricWindow(QWidget):
    EDGE_MARGIN = 8  # 边缘判定宽度
 
    def __init__(self):
        super().__init__()
        self.setWindowFlags(
            Qt.FramelessWindowHint |
            Qt.WindowStaysOnTopHint |
            Qt.Tool
        )
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowOpacity(0.85# 半透明
        self.lyric = FloatingLyricLabel()  # 只显示2行
        layout = QVBoxLayout()
        layout.setContentsMargins(16, 16, 16, 16)
        layout.addWidget(self.lyric)
        self.setLayout(layout)
        self.resize(800, 100)
        desktop = QApplication.desktop()
        self.move(
            (desktop.width() - self.width()) // 2,
            desktop.height() - 150
        )
        # 拖动和缩放相关
        self._move_drag = False
        self._move_DragPosition = None
        self._resize_drag = False
        self._resize_dir = None
 
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        rect = self.rect()
        color = QColor(30, 30, 30, 200# 深色半透明
        painter.setBrush(color)
        painter.setPen(Qt.NoPen)
        painter.drawRoundedRect(rect, 18, 18)
 
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            pos = event.pos()
            margin = self.EDGE_MARGIN
            rect = self.rect()
            # 判断是否在边缘
            if pos.x() < margin and pos.y() < margin:
                self._resize_drag = True
                self._resize_dir = 'topleft'
            elif pos.x() > rect.width() - margin and pos.y() < margin:
                self._resize_drag = True
                self._resize_dir = 'topright'
            elif pos.x() < margin and pos.y() > rect.height() - margin:
                self._resize_drag = True
                self._resize_dir = 'bottomleft'
            elif pos.x() > rect.width() - margin and pos.y() > rect.height() - margin:
                self._resize_drag = True
                self._resize_dir = 'bottomright'
            elif pos.x() < margin:
                self._resize_drag = True
                self._resize_dir = 'left'
            elif pos.x() > rect.width() - margin:
                self._resize_drag = True
                self._resize_dir = 'right'
            elif pos.y() < margin:
                self._resize_drag = True
                self._resize_dir = 'top'
            elif pos.y() > rect.height() - margin:
                self._resize_drag = True
                self._resize_dir = 'bottom'
            else:
                self._move_drag = True
                self._move_DragPosition = event.globalPos() - self.pos()
            event.accept()
 
    def mouseMoveEvent(self, event):
        if self._move_drag and event.buttons() == Qt.LeftButton:
            self.move(event.globalPos() - self._move_DragPosition)
            event.accept()
        elif self._resize_drag and event.buttons() == Qt.LeftButton:
            gpos = event.globalPos()
            geo = self.geometry()
            minw, minh = 200, 50
            if self._resize_dir == 'left':
                diff = gpos.x() - geo.x()
                neww = geo.width() - diff
                if neww > minw:
                    geo.setLeft(gpos.x())
            elif self._resize_dir == 'right':
                neww = gpos.x() - geo.x()
                if neww > minw:
                    geo.setWidth(neww)
            elif self._resize_dir == 'top':
                diff = gpos.y() - geo.y()
                newh = geo.height() - diff
                if newh > minh:
                    geo.setTop(gpos.y())
            elif self._resize_dir == 'bottom':
                newh = gpos.y() - geo.y()
                if newh > minh:
                    geo.setHeight(newh)
            elif self._resize_dir == 'topleft':
                diffx = gpos.x() - geo.x()
                diffy = gpos.y() - geo.y()
                neww = geo.width() - diffx
                newh = geo.height() - diffy
                if neww > minw:
                    geo.setLeft(gpos.x())
                if newh > minh:
                    geo.setTop(gpos.y())
            elif self._resize_dir == 'topright':
                diffy = gpos.y() - geo.y()
                neww = gpos.x() - geo.x()
                newh = geo.height() - diffy
                if neww > minw:
                    geo.setWidth(neww)
                if newh > minh:
                    geo.setTop(gpos.y())
            elif self._resize_dir == 'bottomleft':
                diffx = gpos.x() - geo.x()
                neww = geo.width() - diffx
                newh = gpos.y() - geo.y()
                if neww > minw:
                    geo.setLeft(gpos.x())
                if newh > minh:
                    geo.setHeight(newh)
            elif self._resize_dir == 'bottomright':
                neww = gpos.x() - geo.x()
                newh = gpos.y() - geo.y()
                if neww > minw:
                    geo.setWidth(neww)
                if newh > minh:
                    geo.setHeight(newh)
            self.setGeometry(geo)
            event.accept()
        # 无论是否拖动,都要设置光标
        self.update_cursor(event.pos())
 
    def mouseReleaseEvent(self, event):
        self._move_drag = False
        self._resize_drag = False
        self._resize_dir = None
 
    def setLyrics(self, lyrics):
        self.lyric.setLyrics(lyrics)
 
    def setCurrentTime(self, time):
        self.lyric.setCurrentTime(time)
 
    def update_cursor(self, pos):
        margin = self.EDGE_MARGIN
        rect = self.rect()
        if (pos.x() < margin and pos.y() < margin) or (pos.x() > rect.width() - margin and pos.y() > rect.height() - margin):
            self.setCursor(Qt.SizeFDiagCursor)
        elif (pos.x() > rect.width() - margin and pos.y() < margin) or (pos.x() < margin and pos.y() > rect.height() - margin):
            self.setCursor(Qt.SizeBDiagCursor)
        elif pos.x() < margin or pos.x() > rect.width() - margin:
            self.setCursor(Qt.SizeHorCursor)
        elif pos.y() < margin or pos.y() > rect.height() - margin:
            self.setCursor(Qt.SizeVerCursor)
        else:
            self.setCursor(Qt.ArrowCursor)
 
    def enterEvent(self, event):
        self.update_cursor(self.mapFromGlobal(QCursor.pos()))
 
    def leaveEvent(self, event):
        self.setCursor(Qt.ArrowCursor)
 
class FloatingLyricLabel(LyricLabel):
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        w, h = self.width(), self.height()
 
        # 只显示当前行和下一行,且排除空行
        lines = []
        idx = self.current_index
        # 找到当前行及下一个非空行
        count = 0
        while idx < len(self.lyrics) and count < 2:
            text = self.lyrics[idx][1].strip()
            if text:
                lines.append(text)
                count += 1
            idx += 1
        # 如果不足两行,补空字符串
        while len(lines) < 2:
            lines.append("")
 
        if not any(lines):
            # 没有歌词,显示demo_text
            if hasattr(self, "demo_text") and self.demo_text:
                font = QFont("微软雅黑", int(h * 0.35), QFont.Bold)
                painter.setFont(font)
                painter.setPen(QColor("#aaa"))
                painter.drawText(0, 0, w, h, Qt.AlignHCenter | Qt.AlignVCenter, self.demo_text)
            return
 
        main_text = lines[0]
        next_text = lines[1]
 
        # 计算主行和下一行的最大字号,兼顾宽度和高度
        def fit_font_size(text, max_font_size, max_width, max_height, bold=False):
            font_size = max_font_size
            while font_size > 10:
                font = QFont("微软雅黑", font_size, QFont.Bold if bold else QFont.Normal)
                painter.setFont(font)
                rect = painter.fontMetrics().boundingRect(text)
                if rect.width() <= max_width * 0.95 and rect.height() <= max_height * 0.95:
                    break
                font_size -= 1
            return font_size
 
        # 预设主行和下一行高度比例
        main_ratio = 0.58
        next_ratio = 0.28
        gap = int(h * 0.08)
        main_max_height = h * main_ratio
        next_max_height = h * next_ratio
 
        # 先用最大高度和宽度分别拟合字号
        main_font_size = fit_font_size(main_text, int(main_max_height), w, main_max_height, bold=True)
        next_font_size = fit_font_size(next_text, int(next_max_height), w, next_max_height)
 
        font_main = QFont("微软雅黑", main_font_size, QFont.Bold)
        font_next = QFont("微软雅黑", next_font_size)
 
        # 重新计算行高
        painter.setFont(font_main)
        main_line_height = painter.fontMetrics().height()
        painter.setFont(font_next)
        next_line_height = painter.fontMetrics().height()
        total_height = main_line_height + next_line_height + gap
        start_y = (h - total_height) // 2
 
        # 当前行:彩虹色高亮
        painter.setFont(font_main)
        grad = QLinearGradient(0, start_y, w, start_y + main_line_height)
        cur_time = getattr(self, "cur_time", 0)
        for j in range(7):
            grad.setColorAt(j/6, QColor.fromHsv(int((j*60 + (cur_time*60)%360)%360), 255, 255))
        painter.setPen(QPen(QBrush(grad), 0))
        painter.drawText(0, int(start_y), w, main_line_height, Qt.AlignHCenter | Qt.AlignVCenter, main_text)
 
        # 下一行:灰色
        painter.setFont(font_next)
        painter.setPen(QColor(180, 180, 180, 180))
        painter.drawText(0, int(start_y + main_line_height + gap), w, next_line_height, Qt.AlignHCenter | Qt.AlignVCenter, next_text)
 
class CustomTitleBar(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setFixedHeight(40)
        self.setStyleSheet("""
            background: #222;
            border-top-left-radius: 18px;
            border-top-right-radius: 18px;
        """)
        layout = QHBoxLayout(self)
        layout.setContentsMargins(16, 0, 8, 0)
        self.title = QLabel("Winamp 音乐播放器")
        self.title.setStyleSheet("color: #fff; font-size: 18px; font-weight: bold;")
        layout.addWidget(self.title)
        layout.addStretch()
        self.btn_min = QPushButton("—")
        self.btn_min.setFixedSize(32, 32)
        self.btn_min.setStyleSheet("color:#fff; background:transparent; font-size:20px; border:none;")
        self.btn_close = QPushButton("×")
        self.btn_close.setFixedSize(32, 32)
        self.btn_close.setStyleSheet("color:#fff; background:transparent; font-size:20px; border:none;")
        layout.addWidget(self.btn_min)
        layout.addWidget(self.btn_close)
        self.btn_min.clicked.connect(self.on_min)
        self.btn_close.clicked.connect(self.on_close)
 
    def on_min(self):
        self.window().showMinimized()
 
    def on_close(self):
        self.window().close()
 
    # 支持拖动窗口
    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self._drag_pos = event.globalPos() - self.window().frameGeometry().topLeft()
            event.accept()
 
    def mouseMoveEvent(self, event):
        if event.buttons() == Qt.LeftButton:
            self.window().move(event.globalPos() - self._drag_pos)
            event.accept()
 
    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen(QColor(17, 17, 17), 2)
        painter.setPen(pen)
        y = self.height() + 4  # 向下移5像素
        painter.drawLine(10, y, self.width() - 10, y)
 
class MP3Player(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.song_list = []  # 歌曲文件路径列表
        self.current_index = -1  # 当前播放索引
        self.player = QMediaPlayer()
        self.vlc_player = vlc.MediaPlayer()
        self.timer = QTimer(self)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.update_progress)
        self.slider_is_pressed = False
        self.loop_mode = False  # False: 顺序播放, True: 随机播放
        self.shuffle_mode = False  # False: 顺序播放, True: 随机播放
        self.default_lyric_text = "深埋生命血脉相连\n用丝绸去润泽你的肌肤"
        self.floating_lyric = FloatingLyricWindow()
        self.floating_lyric_visible = False
        self.is_muted = False
        self.btn_mute = QPushButton("&#128266;")
        self.btn_mute.setFixedSize(48, 48)
        self.btn_mute.setStyleSheet("font-size: 24px; background: #333; color: #fff; border-radius: 24px; font-weight: bold;")
        self.btn_mute.clicked.connect(self.toggle_mute)
        self.initUI()
        self.load_last_playlist()
 
    def initUI(self):
        self.song_path = "test.mp3"  # 默认MP3文件路径
        self.cover = CoverWidget(resource_path("fm.png"))
        self.lyric = LyricLabel()
        self.lyric.setDemoText(self.default_lyric_text)
 
        first_row = QHBoxLayout()
        first_row.addWidget(self.cover, 1)
        first_row.addWidget(self.lyric, 2)
 
        # 第二行
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, 100)
        self.slider.setValue(0)
        self.time_label_left = QLabel("00:00")
        self.time_label_right = QLabel("05:27")
        self.time_label_left.setStyleSheet("color: #aaa;")
        self.time_label_right.setStyleSheet("color: #aaa;")
 
        second_row = QHBoxLayout()
        second_row.addWidget(self.time_label_left)
        second_row.addWidget(self.slider, 1)
        second_row.addWidget(self.time_label_right)
 
        # 第三行
        self.btn_prev = QPushButton("&#9198;")
        self.btn_play = QPushButton("&#9654;")
        self.btn_next = QPushButton("&#9197;")
        self.btn_loop = QPushButton("&#128257;")
        self.btn_stop = QPushButton("&#9209;")
        self.btn_add_file = QPushButton("添加文件")
        self.btn_add_dir = QPushButton("添加目录")
        self.btn_save_list = QPushButton("保存列表")
        self.btn_load_list = QPushButton("加载列表")
        self.btn_mute = QPushButton("&#128266;")
        self.btn_float_lyric = QPushButton("词")
        button_style = """
        QPushButton {
            font-size: 24px;
            background: #333;
            color: #fff;
            border-radius: 24px;
            font-weight: bold;
            border: none;
        }
        QPushButton:hover {
            background: #09f;
            color: #fff;
        }
        """
        for btn in [self.btn_prev, self.btn_play, self.btn_next, self.btn_loop, self.btn_stop, self.btn_mute, self.btn_float_lyric]:
            btn.setFixedSize(48, 48)
            btn.setStyleSheet(button_style)
        list_button_style = """
        QPushButton {
            font-size: 16px;
            background: #555;
            color: #fff;
            border-radius: 8px;
            padding: 6px 18px;
            border: none;
        }
        QPushButton:hover {
            background: #09f;
            color: #fff;
        }
        """
        self.btn_add_file.setFixedSize(100, 36)
        self.btn_add_dir.setFixedSize(100, 36)
        self.btn_save_list.setFixedSize(100, 36)
        self.btn_load_list.setFixedSize(100, 36)
        self.btn_add_file.setStyleSheet(list_button_style)
        self.btn_add_dir.setStyleSheet(list_button_style)
        self.btn_save_list.setStyleSheet(list_button_style)
        self.btn_load_list.setStyleSheet(list_button_style)
 
        self.btn_add_file.clicked.connect(self.open_file)
        self.btn_add_dir.clicked.connect(self.open_dir)
        self.btn_save_list.clicked.connect(self.save_playlist)
        self.btn_load_list.clicked.connect(self.load_playlist)
        self.btn_prev.clicked.connect(self.play_prev)
        self.btn_next.clicked.connect(self.play_next)
        self.btn_play.clicked.connect(self.play_selected)
        self.btn_loop.clicked.connect(self.toggle_shuffle_mode)
        self.btn_stop.clicked.connect(self.stop_play)
        self.btn_mute.clicked.connect(self.toggle_mute)
        self.btn_float_lyric.clicked.connect(self.toggle_floating_lyric)
 
        third_row = QHBoxLayout()
        third_row.setSpacing(8# 设置按钮间距
        third_row.addStretch()
        for btn in [self.btn_prev, self.btn_play, self.btn_next, self.btn_loop, self.btn_stop, self.btn_mute, self.btn_float_lyric]:
            third_row.addWidget(btn)
        third_row.addSpacing(20)
        third_row.addWidget(self.btn_add_file)
        third_row.addWidget(self.btn_add_dir)
        third_row.addWidget(self.btn_save_list)
        third_row.addWidget(self.btn_load_list)
        third_row.addStretch()
 
        # 新增:播放列表
        self.list_widget = PlaylistWidget(self)
        self.list_widget.itemDoubleClicked.connect(self.on_item_double_clicked)
        self.list_widget.favSong.connect(self.append_to_fav)
 
        # 总体布局
        main_widget = QWidget(self)
        main_widget.setObjectName("main_widget")
        main_widget.setStyleSheet("""
            #main_widget {
                background: #222;
                border-radius: 18px;
            }
        """)
        main_layout = QVBoxLayout(main_widget)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
 
        self.title_bar = CustomTitleBar(self)
        main_layout.addWidget(self.title_bar)
 
        content_layout = QVBoxLayout()
        content_layout.addLayout(first_row, 3)
        content_layout.addLayout(second_row, 1)
        content_layout.addLayout(third_row, 1)
        content_layout.addWidget(self.list_widget, 2)
        content_layout.setContentsMargins(16, 0, 16, 16)
        main_layout.addLayout(content_layout)
 
        self.setLayout(QVBoxLayout())
        self.layout().addWidget(main_widget)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.resize(1000, 700)
 
        self.slider.sliderPressed.connect(self.on_slider_pressed)
        self.slider.sliderReleased.connect(self.on_slider_released)
        self.slider.sliderMoved.connect(self.on_slider_moved)
 
        self.update_shuffle_button_style()
 
        print(f"初始按钮文本: {self.btn_loop.text()}")
 
        # 添加滚动条样式
        scrollbar_style = """
        QScrollBar:vertical {
            background: #222;
            width: 14px;
            margin: 4px 2px 4px 2px;
            border-radius: 7px;
        }
        QScrollBar::handle:vertical {
            background: #444;
            min-height: 40px;
            border-radius: 7px;
        }
        QScrollBar::handle:vertical:hover {
            background: #09f;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            background: none;
            height: 0px;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
        QScrollBar:horizontal {
            background: #222;
            height: 14px;
            margin: 2px 4px 2px 4px;
            border-radius: 7px;
        }
        QScrollBar::handle:horizontal {
            background: #444;
            min-width: 40px;
            border-radius: 7px;
        }
        QScrollBar::handle:horizontal:hover {
            background: #09f;
        }
        QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal {
            background: none;
            width: 0px;
        }
        QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal {
            background: none;
        }
        """
        self.list_widget.verticalScrollBar().setStyleSheet(scrollbar_style)
        self.list_widget.horizontalScrollBar().setStyleSheet(scrollbar_style)
 
        self.load_last_playlist()
 
    def open_file(self):
        files, _ = QFileDialog.getOpenFileNames(self, "选择音频文件", "", "音频文件 (*.mp3 *.wav *.flac);;所有文件 (*)")
        for file in files:
            self.add_song(file)
 
    def open_dir(self):
        dir_path = QFileDialog.getExistingDirectory(self, "选择文件夹", "")
        if dir_path:
            for root, dirs, files in os.walk(dir_path):
                for fname in files:
                    if fname.lower().endswith(('.mp3', '.wav', '.flac')):
                        self.add_song(os.path.join(root, fname))
 
    def add_song(self, file):
        if file not in self.song_list:
            self.song_list.append(file)
            item = QListWidgetItem(os.path.basename(file))
            item.setToolTip(file)
            self.list_widget.addItem(item)
            # 如果是第一首,自动选中
            if len(self.song_list) == 1:
                self.list_widget.setCurrentRow(0)
                self.play_selected()
 
    def on_item_double_clicked(self, item):
        row = self.list_widget.row(item)
        self.sync_song_list()
        self.current_index = row
        self.play_song_by_index(row)
 
    def play_selected(self):
        row = self.list_widget.currentRow()
        self.sync_song_list()
        if row >= 0:
            self.current_index = row
            state = self.vlc_player.get_state()
            if state in (vlc.State.Playing, vlc.State.Buffering):
                self.vlc_player.pause()
            elif state == vlc.State.Paused:
                self.vlc_player.play()  # 继续播放
            elif state in (vlc.State.Stopped, vlc.State.Ended, vlc.State.NothingSpecial):
                self.play_song_by_index(row)
 
    def play_song_by_index(self, idx):
        if 0 <= idx < len(self.song_list):
            self.current_index = idx
            song_path = self.song_list[idx]
            self.cover.setCover(song_path)
            self.list_widget.setCurrentRow(idx)
            self.vlc_player.stop()
            self.vlc_player.set_media(vlc.Media(song_path))
            self.vlc_player.play()
            self.timer.start()
            self.slider.setValue(0)
            self.time_label_left.setText("00:00")
            self.time_label_right.setText("--:--")
            print(f"播放:{song_path}")
            # 加载歌词
            try:
                lrc = self.load_lrc(song_path) or self.load_embedded_lyric(song_path)
                if lrc:
                    parsed = parse_lrc(lrc)
                    if parsed:
                        self.lyrics_parsed = parsed
                        self.lyric.setLyrics(self.lyrics_parsed)
                        self.floating_lyric.setLyrics(self.lyrics_parsed)  # 同步到浮动歌词
                    else:
                        self.lyric.setDemoText(self.default_lyric_text)
                        self.floating_lyric.setLyrics([])
                else:
                    self.lyric.setDemoText(self.default_lyric_text)
                    self.floating_lyric.setLyrics([])
            except Exception as e:
                self.lyric.setDemoText(self.default_lyric_text)
                self.floating_lyric.setLyrics([])
 
    def play_prev(self):
        if self.song_list:
            if self.shuffle_mode:
                # 随机模式:随机选择一首(避免当前曲目)
                import random
                candidates = [i for i in range(len(self.song_list)) if i != self.current_index]
                if candidates:
                    self.current_index = random.choice(candidates)
                else:
                    self.current_index = self.current_index
            else:
                # 顺序模式:播放上一首
                self.current_index = (self.current_index - 1) % len(self.song_list)
            self.play_song_by_index(self.current_index)
 
    def play_next(self):
        if self.song_list:
            if self.shuffle_mode:
                # 随机模式:随机选择一首(避免当前曲目)
                import random
                candidates = [i for i in range(len(self.song_list)) if i != self.current_index]
                if candidates:
                    self.current_index = random.choice(candidates)
                else:
                    self.current_index = self.current_index
            else:
                # 顺序模式:播放下一首
                self.current_index = (self.current_index + 1) % len(self.song_list)
            self.play_song_by_index(self.current_index)
 
    def on_slider_pressed(self):
        self.slider_is_pressed = True
 
    def on_slider_released(self):
        self.slider_is_pressed = False
        total = self.vlc_player.get_length()
        if total > 0:
            pos = self.slider.value() / 100
            self.vlc_player.set_time(int(total * pos))
 
    def on_slider_moved(self, value):
        total = self.vlc_player.get_length()
        if total > 0:
            cur_time = int(total * value / 100)
            self.time_label_left.setText(self.ms_to_mmss(cur_time))
 
    def update_progress(self):
        if self.vlc_player.is_playing() and not self.slider_is_pressed:
            total = self.vlc_player.get_length()
            cur = self.vlc_player.get_time()
            if total > 0:
                percent = int(cur / total * 100)
                self.slider.setValue(percent)
                self.time_label_left.setText(self.ms_to_mmss(cur))
                self.time_label_right.setText(self.ms_to_mmss(total))
            else:
                self.slider.setValue(0)
                self.time_label_right.setText("--:--")
        elif not self.vlc_player.is_playing():
            if self.vlc_player.get_state() == vlc.State.Ended:
                if self.shuffle_mode:
                    import random
                    if self.song_list:
                        # 避免重复播放当前曲目
                        candidates = [i for i in range(len(self.song_list)) if i != self.current_index]
                        if candidates:
                            next_index = random.choice(candidates)
                        else:
                            next_index = self.current_index
                        self.play_song_by_index(next_index)
                else:
                    self.play_next()
        # 图标联动
        state = self.vlc_player.get_state()
        if state in (vlc.State.Playing, vlc.State.Buffering):
            self.btn_play.setText("&#9208;")
        else:
            self.btn_play.setText("&#9654;")
 
        if hasattr(self, "lyric") and hasattr(self, "lyrics_parsed"):
            cur = self.vlc_player.get_time() / 1000
            self.lyric.setCurrentTime(cur)
            self.floating_lyric.setCurrentTime(cur)  # 同步到浮动歌词
 
    def ms_to_mmss(self, ms):
        s = int(ms // 1000)
        m = s // 60
        s = s % 60
        return f"{m:02d}:{s:02d}"
 
    def save_playlist(self):
        self.sync_song_list()
        file_path, _ = QFileDialog.getSaveFileName(self, "保存播放列表", "", "播放列表文件 (*.m3u *.txt);;所有文件 (*)")
        if file_path:
            try:
                with open(file_path, "w", encoding="utf-8") as f:
                    for song in self.song_list:
                        f.write(song + "\n")
            except Exception as e:
                print("保存失败:", e)
 
    def load_playlist(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "加载播放列表", "", "播放列表文件 (*.m3u *.txt);;所有文件 (*)")
        if file_path:
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    lines = [line.strip() for line in f if line.strip()]
                self.song_list.clear()
                self.list_widget.clear()
                for song in lines:
                    if os.path.exists(song):
                        self.song_list.append(song)
                        item = QListWidgetItem(os.path.basename(song))
                        item.setToolTip(song)
                        self.list_widget.addItem(item)
                if self.song_list:
                    self.list_widget.setCurrentRow(0)
                    self.play_song_by_index(0)
                # 保存最后一次歌单路径
                with open("last_playlist.txt", "w", encoding="utf-8") as f:
                    f.write(file_path)
            except Exception as e:
                print("加载失败:", e)
 
    def sync_song_list(self):
        self.song_list = []
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            if item and item.toolTip():
                self.song_list.append(item.toolTip())
 
    def toggle_shuffle_mode(self):
        self.shuffle_mode = not self.shuffle_mode
        self.update_shuffle_button_style()
        print(f"切换后模式: {self.shuffle_mode}, 按钮文本: {self.btn_loop.text()}")
 
    def stop_play(self):
        self.vlc_player.stop()
        self.timer.stop()
        self.slider.setValue(0)
        self.time_label_left.setText("00:00")
        self.time_label_right.setText("--:--")
        self.lyric.setDemoText(self.default_lyric_text)
        self.append_to_fav(self.song_list[self.current_index])
 
    def update_shuffle_button_style(self):
        if self.shuffle_mode:
            self.btn_loop.setText("&#128256;")
        else:
            self.btn_loop.setText("&#128257;")
        self.btn_loop.update()  # 强制刷新按钮
 
    def load_lrc(self, song_path):
        lrc_path = os.path.splitext(song_path)[0] + ".lrc"
        if os.path.exists(lrc_path):
            with open(lrc_path, encoding="utf-8") as f:
                return f.read()
        return None
 
    def load_embedded_lyric(self, song_path):
        try:
            audio = MP3(song_path, ID3=ID3)
            for tag in audio.tags.values():
                if tag.FrameID == "USLT":
                    return tag.text
        except Exception:
            pass
        return None
 
    def toggle_floating_lyric(self):
        if self.floating_lyric_visible:
            self.floating_lyric.hide()
            self.floating_lyric_visible = False
            self.btn_float_lyric.setStyleSheet(
                "font-size: 24px; background: #333; color: #fff; border-radius: 24px; font-weight: bold;"
            )
        else:
            self.floating_lyric.show()
            self.floating_lyric_visible = True
            self.btn_float_lyric.setStyleSheet(
                "font-size: 24px; background: #09f; color: #fff; border-radius: 24px; font-weight: bold;"
            )
 
    def toggle_mute(self):
        self.is_muted = not self.is_muted
        self.vlc_player.audio_set_mute(self.is_muted)
        if self.is_muted:
            self.btn_mute.setText("&#128263;")
            self.btn_mute.setStyleSheet("font-size: 24px; background: #09f; color: #fff; border-radius: 24px; font-weight: bold;")
        else:
            self.btn_mute.setText("&#128266;")
            self.btn_mute.setStyleSheet("font-size: 24px; background: #333; color: #fff; border-radius: 24px; font-weight: bold;")
 
    def append_to_fav(self, song):
        fav_path = os.path.abspath("收藏歌单.m3u")
        try:
            need_header = not os.path.exists(fav_path)
            if os.path.exists(fav_path):
                with open(fav_path, "r", encoding="utf-8") as f:
                    lines = [line.strip() for line in f if line.strip()]
                if song in lines:
                    return
            with open(fav_path, "a", encoding="utf-8") as f:
                if need_header:
                    f.write("#EXTM3U\n")
                f.write(song + "\n")
            print(f"已收藏到: {fav_path}"# 调试用
        except Exception as e:
            print("收藏失败:", e)
 
    def load_last_playlist(self):
        try:
            if os.path.exists("last_playlist.txt"):
                with open("last_playlist.txt", "r", encoding="utf-8") as f:
                    file_path = f.read().strip()
                if file_path and os.path.exists(file_path):
                    with open(file_path, "r", encoding="utf-8") as f:
                        lines = [line.strip() for line in f if line.strip()]
                    self.song_list.clear()
                    self.list_widget.clear()
                    for song in lines:
                        if os.path.exists(song):
                            self.song_list.append(song)
                            item = QListWidgetItem(os.path.basename(song))
                            item.setToolTip(song)
                            self.list_widget.addItem(item)
                    if self.song_list:
                        self.list_widget.setCurrentRow(0)
                        self.play_song_by_index(0)
        except Exception as e:
            print("自动加载上次歌单失败:", e)
 
def parse_lrc(lrc_text):
    pattern = re.compile(r"\[(\d+):(\d+)(?:\.(\d+))?\](.*)")
    result = []
    for line in lrc_text.splitlines():
        m = pattern.match(line)
        if m:
            minute = int(m.group(1))
            second = int(m.group(2))
            ms = int(m.group(3) or 0)
            time = minute * 60 + second + ms / 100 if ms else minute * 60 + second
            text = m.group(4).strip()
            result.append((time, text))
    result.sort()
    return result
 
if __name__ == "__main__":
    app = QApplication(sys.argv)
    player = MP3Player()
    player.show()
    print("当前工作目录:", os.getcwd())
    sys.exit(app.exec_())




111.png

免费评分

参与人数 6吾爱币 +13 热心值 +6 收起 理由
pj2015 + 1 + 1 我很赞同!
ronalp + 1 + 1 我很赞同!
苏紫方璇 + 7 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
weidechan + 1 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!
wanfon + 1 + 1 热心回复!
smile1110 + 2 + 1 nb兄弟,加油

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

ciocoinwnnw 发表于 2025-5-14 17:06
楼主,真是厉害!短短时间内就搞出一个这么好看的音乐播放器,而且功能还这么强大。黑胶唱片封面和浮动歌词特别有感觉,完全提升了听歌体验。用GPT-4.1写的代码也让我很感慨AI的发展,居然能帮助开发出这么复杂的应用。
 楼主| liuyang207 发表于 2025-5-13 20:35
下载提供最新的编译版本了,界面美化了一下,感觉差不多了。
动态的唱针移动,光影流动的背景等等。
https://www.alipan.com/s/w2eqoL2fZbw
winamp1.33.png
liutao0474 发表于 2025-4-30 16:28
zqfbz 发表于 2025-4-30 16:31
程序员要下岗了!!!
qsxls 发表于 2025-4-30 16:32
这个好,可以玩还可以学习。谢谢楼主分享
ailiwude 发表于 2025-4-30 16:36
谢谢谢谢谢谢
xk1539287520 发表于 2025-4-30 16:42
大佬能写个wince使用的吗?
Open 发表于 2025-4-30 16:49
AI增加了便利性
shimeng0624 发表于 2025-4-30 17:27
AI带的便利是有好有坏呀,期待有更大的突破。
nur11111 发表于 2025-4-30 17:43
zqfbz 发表于 2025-4-30 16:31
程序员要下岗了!!!

确实,大厂程序员应该裁员90%,AI上就完事了
yy964140711 发表于 2025-4-30 17:56
又有一波程序员要下岗了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-5-25 18:08

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表