好友
阅读权限10
听众
最后登录1970-1-1
|
# -*- coding: utf-8 -*-
"""
爱听音乐播放器(修复主要BUG版本)
基于 https://www.2t58.com 接口
依赖: pip install requests pycryptodome PyQt6 pillow PyQt6-WebEngine
"""
import sys, os, requests, binascii, re, tempfile, json, enum, traceback
os.chdir(os.path.dirname(os.path.abspath(__file__)))
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLineEdit, QPushButton, QListWidget,
QListWidgetItem, QLabel, QSlider, QTextEdit,
QSplitter, QMessageBox, QScrollArea, QFrame,
QFileDialog, QMenu, QDialog)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QUrl, QTimer
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
from PyQt6.QtGui import QPixmap, QTextCursor
from PyQt6.QtWebEngineWidgets import QWebEngineView
# ============ 接口配置 ============
BASE = "https://www.2t58.com"
PLAY_API = BASE + "/js/play.php"
LRC_API = "https://js.eev3.com/lrc.php"
AES_KEY = binascii.unhexlify("8a5a0271acadce264fbd5492e999a25f19abd19258fbc8252e1d9fcd69adb7bf")
COOKIE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cookies.json")
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36",
"Referer": BASE + "/",
})
def _load_cookies():
try:
if os.path.exists(COOKIE_FILE):
with open(COOKIE_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
for k, v in data.items():
session.cookies.set(k, v, domain=".2t58.com")
except Exception as e:
print(f"加载cookie异常:{e}")
_load_cookies()
def _save_cookies():
try:
data = {}
for c in session.cookies:
data[c.name] = c.value
with open(COOKIE_FILE, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as e:
print(f"保存cookie异常:{e}")
# 榜单配置
CHARTS = [
("热门", "/"),
("新歌", "/list/new.html"),
("TOP榜", "/list/top.html"),
("DJ舞曲", "/list/djwuqu.html"),
("抖音热歌", "/list/douyin.html"),
("网络红歌", "/list/hot.html"),
("粤语金曲", "/list/yytop.html"),
("欧美金曲", "/list/ustop.html"),
("古风", "/list/gfhot.html"),
("影视金曲", "/list/ystop.html"),
("ACG", "/list/newacg.html"),
("说唱", "/list/sctop.html"),
("80后", "/list/blhot.html"),
("网红", "/list/wlhot.html"),
("电音", "/list/dytop.html"),
("酷我飙升", "/list/kuwo.html"),
("车载", "/list/cztop.html"),
("KTV", "/list/ktvtop.html"),
("睡前", "/list/sqtop.html"),
("跑步", "/list/jstop.html"),
]
# ============ 核心接口 ============
def decrypt_url(enc_hex):
ct = binascii.unhexlify(enc_hex)
pt = unpad(AES.new(AES_KEY, AES.MODE_ECB).decrypt(ct), AES.block_size)
return pt.decode("utf-8")
def get_song_info(song_id, retry=3):
last_err = None
for i in range(retry):
try:
r = session.post(PLAY_API, data={"id": song_id, "type": "music"},
headers={"X-Requested-With": "XMLHttpRequest"}, timeout=10)
j = r.json()
if j.get("msg") != 1:
raise Exception(j.get("error", "获取播放地址返回错误"))
return {"url": decrypt_url(j["url"]), "pic": j["pic"], "lkid": j["lkid"]}
except Exception as e:
last_err = e
print(f"get_song_info 重试{i+1}失败 {e}")
raise last_err
def get_lyrics(lkid):
try:
r = session.get(LRC_API, params={"cid": lkid}, timeout=10)
return r.json().get("lrc", "")
except Exception as e:
print(f"获取歌词异常:{e}")
return ""
def parse_lrc(lrc_text):
"""修复:支持一行多个时间标签,过滤元标签[ti:][ar:]"""
result = []
time_pat = re.compile(r"\[(\d+):(\d+(?:\.\d+)?)\]")
for line in lrc_text.splitlines():
line = line.rstrip("\r\n")
if re.match(r"^\[(ti|ar|al|by|offset):", line.strip()):
continue
times = time_pat.findall(line)
if not times:
continue
lyric_text = time_pat.sub("", line).strip()
for m in times:
t = int(m[0]) * 60 + float(m[1])
result.append((t, lyric_text))
result.sort(key=lambda x: x[0])
return result
def _extract_songs(html):
songs, seen = [], set()
pat = re.compile(r'href="/song/([^"]+)\.html"[^>]*>([^<]+)</a>')
for m in pat.finditer(html):
sid, name = m.group(1), m.group(2).strip()
if sid not in seen and name:
seen.add(sid)
songs.append({"id": sid, "title": name})
return songs
def _get_with_retry(url, **kw):
kw.setdefault("timeout", 30)
last = None
for i in range(3):
try:
return session.get(url, **kw)
except Exception as e:
last = e
print(f"GET重试{i+1}失败 {e}")
raise last
def fetch_url_songs(path):
r = _get_with_retry(BASE + path)
r.encoding = r.apparent_encoding or "utf-8"
if "安全验证" in r.text and len(r.text) < 3000:
raise Exception("需要人机验证")
return _extract_songs(r.text)
def search_songs(keyword):
r = _get_with_retry(f"{BASE}/so/{requests.utils.quote(keyword)}.html")
r.encoding = r.apparent_encoding or "utf-8"
return _extract_songs(r.text)
# ============ 后台线程 ============
class LoadSongsThread(QThread):
done = pyqtSignal(list)
fail = pyqtSignal(str)
def __init__(self, path=None, keyword=None):
super().__init__()
self.path = path
self.keyword = keyword
def run(self):
try:
if self.keyword:
songs = search_songs(self.keyword)
else:
songs = fetch_url_songs(self.path)
self.done.emit(songs)
except Exception as e:
self.fail.emit(str(e))
class PlayThread(QThread):
done = pyqtSignal(dict)
fail = pyqtSignal(str)
def __init__(self, song):
super().__init__()
self.song = song
def run(self):
try:
info = get_song_info(self.song["id"])
ar = session.get(info["url"], headers={"Referer": "https://www.kuwo.cn/"},
timeout=60, stream=True)
tmp = tempfile.NamedTemporaryFile(suffix=".m4a", delete=False)
total = 0
for chunk in ar.iter_content(chunk_size=8192):
if self.isInterruptionRequested():
tmp.close()
os.unlink(tmp.name)
return
if chunk:
tmp.write(chunk)
total += len(chunk)
tmp.close()
if total < 50000:
os.unlink(tmp.name)
raise Exception("音频下载失败(403或不完整)")
lrc = get_lyrics(info["lkid"])
pic_data = b""
try:
pr = session.get(info["pic"], headers={"Referer": "https://www.kuwo.cn/"}, timeout=10)
if pr.status_code == 200 and len(pr.content) > 500:
pic_data = pr.content
except Exception as e:
print(f"封面下载异常:{e}")
self.done.emit({"song": self.song, "info": info, "path": tmp.name,
"lrc": lrc, "pic": pic_data})
except Exception as e:
self.fail.emit(str(e))
class DownloadThread(QThread):
done = pyqtSignal(str)
fail = pyqtSignal(str)
def __init__(self, song, save_path):
super().__init__()
self.song = song
self.save_path = save_path
def run(self):
try:
info = get_song_info(self.song["id"])
ar = session.get(info["url"], headers={"Referer": "https://www.kuwo.cn/"},
timeout=60, stream=True)
total = 0
with open(self.save_path, "wb") as f:
for chunk in ar.iter_content(chunk_size=8192):
if self.isInterruptionRequested():
return
if chunk:
f.write(chunk)
total += len(chunk)
if total < 50000:
os.unlink(self.save_path)
raise Exception("下载失败,文件过小")
self.done.emit(self.save_path)
except Exception as e:
self.fail.emit(str(e))
# ============ 人机验证对话框 ============
class VerifyDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("请完成人机验证")
self.resize(800, 650)
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.web = QWebEngineView()
self.web.setUrl(QUrl(BASE + "/"))
layout.addWidget(self.web, 1)
bottom_bar = QHBoxLayout()
bottom_bar.setContentsMargins(10, 6, 10, 6)
tip = QLabel("勾选\"我不是人机\",看到网站首页后,点下面按钮继续")
tip.setStyleSheet("color: #888; font-size: 12px;")
bottom_bar.addWidget(tip, 1)
btn_ok = QPushButton("验证完成,继续")
btn_ok.setStyleSheet("background: #e94560; color: white; padding: 6px 20px;")
btn_ok.clicked.connect(self._finish)
bottom_bar.addWidget(btn_ok)
layout.addLayout(bottom_bar)
self.cookies = {}
def _finish(self):
counter = [2]
def js_cb(cookie_str):
try:
if cookie_str:
for part in cookie_str.split(";"):
part = part.strip()
if "=" in part:
name, value = part.split("=", 1)
name = name.strip()
value = value.strip()
if name:
self.cookies[name] = value
except Exception:
pass
counter[0] -= 1
if counter[0] <= 0:
self.accept()
def store_cb(cookies):
try:
for c in cookies:
try:
name = bytes(c.name()).decode("utf-8", errors="ignore")
value = bytes(c.value()).decode("utf-8", errors="ignore")
if name and "2t58" in c.domain():
self.cookies[name] = value
except Exception:
pass
except Exception:
pass
counter[0] -= 1
if counter[0] <= 0:
self.accept()
try:
self.web.page().runJavaScript("document.cookie", js_cb)
except Exception:
counter[0] -= 1
try:
self.web.page().cookieStore().getAllCookies(store_cb)
except Exception:
counter[0] -= 1
if counter[0] <= 0:
self.accept()
class PlayMode(enum.Enum):
LIST_LOOP = 0
SINGLE_LOOP = 1
NO_LOOP = 2
# ============ 主窗口 ============
class PlayerWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("2t58 音乐播放器(修复版)")
self.resize(960, 720)
self.setStyleSheet("""
QMainWindow, QWidget { background: #1a1a2e; color: #e0e0e0; }
QLineEdit { background: #16213e; border: 1px solid #0f3460; padding: 6px; border-radius: 4px; }
QPushButton { background: #0f3460; border: none; padding: 5px 12px; border-radius: 4px; font-size: 12px; }
QPushButton:hover { background: #163a5f; }
QPushButton#chartBtn { background: #16213e; padding: 4px 10px; }
QPushButton#chartBtn:hover { background: #e94560; }
QPushButton#chartActive { background: #e94560; color: white; padding: 4px 10px; }
QListWidget { background: #16213e; border: none; font-size: 13px; }
QListWidget::item { padding: 6px; }
QListWidget::item:selected { background: #e94560; color: white; }
QSlider::groove:horizontal { height: 6px; background: #0f3460; border-radius: 3px; }
QSlider::handle:horizontal { width: 14px; height: 14px; margin: -4px 0; background: #e94560; border-radius: 7px; }
QTextEdit { background: #16213e; border: none; font-size: 14px; color: #a0a0b0; }
QLabel { color: #e0e0e0; }
QScrollArea { border: none; background: #1a1a2e; }
""")
self.player = QMediaPlayer()
self.audio = QAudioOutput()
self.player.setAudioOutput(self.audio)
self.audio.setVolume(0.5)
self.playlist = []
self.current_idx = -1
self.lrc_lines = []
self.lrc_idx = 0
self.temp_path = None
self.is_playing = False
self.chart_btns = {}
self.slider_dragging = False
self.play_mode = PlayMode.LIST_LOOP
self._load_lock = False
self._th: LoadSongsThread | None = None
self._pth: PlayThread | None = None
self._dth: DownloadThread | None = None
self._build_ui()
self._load_chart("/", "热门")
QTimer.singleShot(300, lambda: self.search_edit.setFocus())
def _build_ui(self):
central = QWidget()
self.setCentralWidget(central)
root = QVBoxLayout(central)
root.setContentsMargins(10, 10, 10, 10)
root.setSpacing(6)
top = QHBoxLayout()
top.addWidget(QLabel("搜索:"))
self.search_edit = QLineEdit()
self.search_edit.setPlaceholderText("输入歌曲名 / 歌手,回车搜索")
self.search_edit.returnPressed.connect(self._do_search)
top.addWidget(self.search_edit, 1)
btn_search = QPushButton("搜索")
btn_search.clicked.connect(self._do_search)
top.addWidget(btn_search)
root.addLayout(top)
chart_scroll = QScrollArea()
chart_scroll.setFixedHeight(44)
chart_scroll.setWidgetResizable(True)
chart_container = QWidget()
chart_layout = QHBoxLayout(chart_container)
chart_layout.setContentsMargins(0, 4, 0, 4)
chart_layout.setSpacing(4)
for name, path in CHARTS:
btn = QPushButton(name)
btn.setObjectName("chartBtn")
btn.clicked.connect(lambda checked, p=path, n=name: self._load_chart(p, n))
chart_layout.addWidget(btn)
self.chart_btns[name] = btn
chart_layout.addStretch()
chart_scroll.setWidget(chart_container)
root.addWidget(chart_scroll)
splitter = QSplitter(Qt.Orientation.Horizontal)
self.list_widget = QListWidget()
self.list_widget.itemDoubleClicked.connect(lambda i: self._play_at(self.list_widget.row(i)))
self.list_widget.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.list_widget.customContextMenuRequested.connect(self._show_list_menu)
splitter.addWidget(self.list_widget)
right = QWidget()
right_layout = QVBoxLayout(right)
right_layout.setContentsMargins(0, 0, 0, 0)
self.cover_label = QLabel()
self.cover_label.setFixedSize(200, 200)
self.cover_label.setStyleSheet("background: #16213e; border-radius: 8px;")
self.cover_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.cover_label.setText("封面")
right_layout.addWidget(self.cover_label, 0, Qt.AlignmentFlag.AlignHCenter)
self.song_label = QLabel("未播放")
self.song_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.song_label.setStyleSheet("font-size: 14px; padding: 4px;")
right_layout.addWidget(self.song_label)
self.lrc_view = QTextEdit()
self.lrc_view.setReadOnly(True)
right_layout.addWidget(self.lrc_view, 1)
splitter.addWidget(right)
splitter.setSizes([380, 560])
root.addWidget(splitter, 1)
bottom = QHBoxLayout()
bottom.setSpacing(12)
self.btn_loop = QPushButton("🔁")
self.btn_loop.setFixedSize(36, 36)
self.btn_loop.setStyleSheet("QPushButton { border: none; font-size: 18px; background: transparent; }")
self.btn_loop.clicked.connect(self._change_play_mode)
bottom.addWidget(self.btn_loop)
btn_prev = QPushButton("⏮")
btn_prev.setFixedSize(40, 40)
btn_prev.setStyleSheet("QPushButton { border: none; font-size: 20px; background: transparent; }")
btn_prev.clicked.connect(self._prev)
bottom.addWidget(btn_prev)
self.btn_play = QPushButton("▶")
self.btn_play.setFixedSize(56, 56)
self.btn_play.setStyleSheet("""
QPushButton { background: #f5c518; border: none; border-radius: 28px;
font-size: 22px; color: #1a1a2e; }
QPushButton:hover { background: #ffd633; }
""")
self.btn_play.clicked.connect(self._toggle_play)
bottom.addWidget(self.btn_play)
btn_next = QPushButton("⏭")
btn_next.setFixedSize(40, 40)
btn_next.setStyleSheet("QPushButton { border: none; font-size: 20px; background: transparent; }")
btn_next.clicked.connect(self._next)
bottom.addWidget(btn_next)
self.time_label = QLabel("00:00 / 00:00")
bottom.addWidget(self.time_label)
self.progress = QSlider(Qt.Orientation.Horizontal)
self.progress.sliderPressed.connect(lambda: setattr(self, "slider_dragging", True))
self.progress.sliderReleased.connect(self._seek)
bottom.addWidget(self.progress, 1)
vol_icon = QLabel("🔊")
vol_icon.setStyleSheet("font-size: 16px;")
bottom.addWidget(vol_icon)
self.vol_slider = QSlider(Qt.Orientation.Horizontal)
self.vol_slider.setFixedWidth(80)
self.vol_slider.setValue(50)
self.vol_slider.valueChanged.connect(lambda v: self.audio.setVolume(v / 100))
bottom.addWidget(self.vol_slider)
root.addLayout(bottom)
self.timer = QTimer()
self.timer.setInterval(500)
self.timer.timeout.connect(self._tick)
self.player.playbackStateChanged.connect(self._on_state_changed)
self.player.mediaStatusChanged.connect(self._on_media_status)
def _change_play_mode(self):
mode_list = [PlayMode.LIST_LOOP, PlayMode.SINGLE_LOOP, PlayMode.NO_LOOP]
idx = mode_list.index(self.play_mode)
self.play_mode = mode_list[(idx + 1) % len(mode_list)]
tip_map = {
PlayMode.LIST_LOOP: "🔁 列表循环",
PlayMode.SINGLE_LOOP: "🔂 单曲循环",
PlayMode.NO_LOOP: "⏹ 播放完毕停止"
}
self.btn_loop.setText({
PlayMode.LIST_LOOP: "🔁",
PlayMode.SINGLE_LOOP: "🔂",
PlayMode.NO_LOOP: "⏹"
}[self.play_mode])
self.song_label.setText(tip_map[self.play_mode])
def _load_chart(self, path, name):
if self._load_lock:
return
self.search_edit.clear()
self.song_label.setText(f"加载: {name}...")
for n, btn in self.chart_btns.items():
btn.setObjectName("chartActive" if n == name else "chartBtn")
btn.style().unpolish(btn)
btn.style().polish(btn)
self._pending_path = path
self._pending_name = name
self._load_lock = True
self._th = LoadSongsThread(path=path)
self._th.done.connect(self._fill_list)
self._th.fail.connect(lambda e: self._on_load_fail(e))
self._th.finished.connect(lambda: setattr(self, "_load_lock", False))
self._th.start()
def _on_load_fail(self, err):
self.song_label.setText("需要人机验证,请在弹出的窗口中勾选验证...")
try:
dlg = VerifyDialog(self)
if dlg.exec():
for k, v in dlg.cookies.items():
session.cookies.set(k, v, domain=".2t58.com")
_save_cookies()
self.song_label.setText(f"重新加载: {self._pending_name}...")
self._load_lock = True
self._th = LoadSongsThread(path=self._pending_path)
self._th.done.connect(self._fill_list)
self._th.fail.connect(lambda e: self.song_label.setText(f"加载失败: {e}"))
self._th.finished.connect(lambda: setattr(self, "_load_lock", False))
self._th.start()
except Exception as e:
self.song_label.setText(f"验证出错: {e}")
def _do_search(self):
kw = self.search_edit.text().strip()
if not kw:
return
if self._load_lock:
return
self.song_label.setText(f"搜索: {kw}...")
for btn in self.chart_btns.values():
btn.setObjectName("chartBtn")
btn.style().unpolish(btn)
btn.style().polish(btn)
self._load_lock = True
self._th = LoadSongsThread(keyword=kw)
self._th.done.connect(self._fill_list)
self._th.fail.connect(lambda e: self.song_label.setText(f"搜索失败: {e}"))
self._th.finished.connect(lambda: setattr(self, "_load_lock", False))
self._th.start()
self.search_edit.setFocus()
self.search_edit.selectAll()
def _fill_list(self, songs):
self.list_widget.clear()
self.playlist = songs
for s in songs:
QListWidgetItem(s["title"], self.list_widget)
self.song_label.setText(f"共 {len(songs)} 首")
def _show_list_menu(self, pos):
item = self.list_widget.itemAt(pos)
if not item:
return
idx = self.list_widget.row(item)
menu = QMenu(self)
menu.setStyleSheet("QMenu { background: #16213e; color: #e0e0e0; } QMenu::item:selected { background: #e94560; }")
act_play = menu.addAction("播放")
act_dl = menu.addAction("下载到...")
act = menu.exec(self.list_widget.viewport().mapToGlobal(pos))
if act == act_play:
self._play_at(idx)
elif act == act_dl:
self._download_song(idx)
def _download_song(self, idx):
if idx < 0 or idx >= len(self.playlist):
return
song = self.playlist[idx]
safe_name = re.sub(r'[\\/:*?"<>|]', '_', song["title"])
path, _ = QFileDialog.getSaveFileName(self, "保存歌曲", f"{safe_name}.m4a", "音频文件 (*.m4a)")
if not path:
return
self.song_label.setText(f"下载中: {song['title']}...")
self._dth = DownloadThread(song, path)
self._dth.done.connect(lambda p: self.song_label.setText(f"已下载: {p}"))
self._dth.fail.connect(lambda e: self.song_label.setText(f"下载失败: {e}"))
self._dth.start()
def _play_at(self, idx):
if idx < 0 or idx >= len(self.playlist):
return
if self._pth and self._pth.isRunning():
self._pth.requestInterruption()
self.current_idx = idx
song = self.playlist[idx]
self.song_label.setText(f"加载: {song['title']}")
self.list_widget.setCurrentRow(idx)
self._pth = PlayThread(song)
self._pth.done.connect(self._start_play)
self._pth.fail.connect(lambda e: self.song_label.setText(f"播放失败: {e}"))
self._pth.start()
def _start_play(self, data):
if self.temp_path and os.path.exists(self.temp_path):
try:
os.unlink(self.temp_path)
except Exception:
pass
self.temp_path = data["path"]
self.lrc_lines = parse_lrc(data["lrc"])
self.lrc_idx = -1
self.lrc_view.clear()
if data["pic"]:
pix = QPixmap()
pix.loadFromData(data["pic"])
if not pix.isNull():
pix = pix.scaled(200, 200, Qt.AspectRatioMode.KeepAspectRatio,
Qt.TransformationMode.SmoothTransformation)
self.cover_label.setPixmap(pix)
else:
self.cover_label.setText("封面")
else:
self.cover_label.setText("封面")
self.song_label.setText(data["song"]["title"])
self.player.setSource(QUrl.fromLocalFile(self.temp_path))
self.player.play()
self.timer.start()
def _toggle_play(self):
if self.current_idx < 0:
if self.playlist:
self._play_at(0)
return
if self.is_playing:
self.player.pause()
else:
self.player.play()
def _prev(self):
if not self.playlist:
return
if self.current_idx > 0:
self._play_index(self.current_idx - 1)
else:
self._play_index(len(self.playlist) - 1)
def _next(self):
if not self.playlist:
return
if self.current_idx < len(self.playlist) - 1:
self._play_index(self.current_idx + 1)
else:
self._play_index(0)
def _play_index(self, idx):
self._play_at(idx)
def _seek(self):
dur = self.player.duration()
if dur > 0:
self.player.setPosition(int(self.progress.value() / 100 * dur))
self.slider_dragging = False
def _on_state_changed(self, state):
self.is_playing = (state == QMediaPlayer.PlaybackState.PlayingState)
self.btn_play.setText("⏸" if self.is_playing else "▶")
def _on_media_status(self, status):
if status == QMediaPlayer.MediaStatus.EndOfMedia and self.current_idx >= 0:
if self.play_mode == PlayMode.SINGLE_LOOP:
self.player.setPosition(0)
self.player.play()
elif self.play_mode == PlayMode.LIST_LOOP:
nxt = self.current_idx + 1
if nxt >= len(self.playlist):
nxt = 0
self._play_at(nxt)
elif self.play_mode == PlayMode.NO_LOOP:
pass
elif status == QMediaPlayer.MediaStatus.InvalidMedia and self.current_idx >= 0:
total_cnt = len(self.playlist)
if total_cnt <= 1:
self.song_label.setText("当前歌曲无法播放,列表无更多曲目")
return
nxt = self.current_idx + 1
if nxt >= total_cnt:
nxt = 0
self.song_label.setText(f"跳过无法播放: {self.playlist[self.current_idx]['title']}")
QTimer.singleShot(300, lambda idx=nxt: self._play_at(idx))
def _tick(self):
dur = self.player.duration()
pos = self.player.position()
if dur > 0:
if not self.slider_dragging:
self.progress.setValue(int(pos / dur * 100))
self.time_label.setText(f"{self._fmt(pos/1000)} / {self._fmt(dur/1000)}")
self._show_lrc(pos / 1000)
def _show_lrc(self, cur):
if not self.lrc_lines:
return
idx = 0
for i, (t, _) in enumerate(self.lrc_lines):
if t <= cur:
idx = i
else:
break
if idx == self.lrc_idx:
return
self.lrc_idx = idx
self.lrc_view.clear()
start = max(0, idx - 5)
end = min(len(self.lrc_lines), idx + 8)
html_parts = []
for i in range(start, end):
line_text = self.lrc_lines[i][1] or "♪"
if i == idx:
html_parts.append(f'<p style="color:#e94560;font-weight:bold;font-size:15px;">{line_text}</p>')
else:
html_parts.append(f'<p style="color:#888;">{line_text}</p>')
self.lrc_view.setHtml("".join(html_parts))
self.lrc_view.moveCursor(QTextCursor.MoveOperation.End)
@staticmethod
def _fmt(sec):
m = int(sec) // 60
s = int(sec) % 60
return f"{m:02d}:{s:02d}"
def closeEvent(self, e):
try:
self.timer.stop()
self.player.stop()
if self._th and self._th.isRunning():
self._th.requestInterruption()
if self._pth and self._pth.isRunning():
self._pth.requestInterruption()
if self._dth and self._dth.isRunning():
self._dth.requestInterruption()
if self.temp_path and os.path.exists(self.temp_path):
os.unlink(self.temp_path)
except Exception as ex:
print(f"关闭窗口清理异常 {ex}")
e.accept()
if __name__ == "__main__":
app = QApplication(sys.argv)
win = PlayerWindow()
win.show()
sys.exit(app.exec())
|
|