仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/player.js 19.2 KB · 607 行 原始文件
1/**
2 * 播放器(迁移自 lx-music-mobile/src/core/player/player.ts + plugins/player)
3 * 基于 uni.getBackgroundAudioManager(背景音频管理器)
4 *
5 * 使用背景音频管理器而非 InnerAudioContext 的原因:
6 * - App 端会注册系统 MediaSession,通知栏/锁屏显示系统媒体播放控件
7 * - 蓝牙耳机线控(AVRCP)可控制播放/暂停
8 * - 切后台可持续播放
9 *
10 * 注意:与 InnerAudioContext 的行为差异:
11 * - 设置 src 后会自动开始播放(需在不需要播放时手动 pause)
12 * - 无 volume/obeyMuteSwitch 属性(音量由系统媒体音量控制)
13 * - title 必填(供系统媒体通知显示)
14 *
15 * 功能:
16 * - 4 种播放模式:列表循环 / 随机 / 顺序 / 单曲循环
17 * - 播放/暂停/上一曲/下一曲/进度跳转
18 * - 播放列表管理
19 */
20import event from './event.js'
21import { getSetting, updateSetting } from './setting.js'
22import { getMusicUrl, getLyricInfo, getPicPath } from './music/index.js'
23import { PLAY_MODE_LIST, SOURCE_NAMES } from './constants.js'
24import { getRandom } from './utils.js'
25import { addListMusics, LIST_IDS, normalizeMusicInfo } from './playlist.js'
26import { initMediaSession, updateMediaState, stopMediaSession } from './media-session.js'
27
28let audio = null
29let playMusicInfo = null // 当前播放音乐信息
30let playList = [] // 当前播放列表
31let playIndex = -1
32let isPlay = false
33let currentTime = 0
34let duration = 0
35/** 播放结束处理重入锁,防止 onTimeUpdate 兜底在 getMusicUrl 异步期间反复触发 */
36let isHandlingEnded = false
37/**
38 * 当前歌曲的歌词。
39 * 播放页是用户点击播放栏后才打开的,此时 playerLyricUpdated 事件早已广播完毕,
40 * 因此必须把歌词留存下来供页面 onLoad 时读取,否则会一直显示"暂无歌词"。
41 */
42let playLyricInfo = { lyric: '', tlyric: '' }
43
44/** 换源(如切换音质)后待跳转的播放进度;音频可播放后执行 seek */
45let pendingSeekTime = null
46
47/** 系统媒体会话进度节流同步时间戳(App-Android) */
48let mediaSyncAt = 0
49
50// ============ 初始化 ============
51
52// #ifdef APP-PLUS
53/**
54 * Android 13+ 通知权限运行时申请。
55 * 系统媒体通知(通知栏/锁屏控件)依赖通知权限,
56 * Android 13(SDK 33)起该权限默认关闭,未授权时媒体通知完全不显示。
57 */
58const requestNotificationPermission = () => {
59 try {
60 const sys = uni.getSystemInfoSync()
61 if (sys.platform !== 'android') return
62 const osVer = parseInt(sys.osVersion) || 0
63 if (osVer < 13) return
64 plus.android.requestPermissions(
65 ['android.permission.POST_NOTIFICATIONS'],
66 (e) => {
67 console.log('[notify permission]', JSON.stringify(e))
68 },
69 (e) => {
70 console.log('[notify permission denied]', JSON.stringify(e))
71 }
72 )
73 } catch (e) {
74 console.log('[notify permission]', e)
75 }
76}
77// #endif
78
79export const initPlayer = () => {
80 if (audio) return
81 audio = uni.getBackgroundAudioManager()
82
83 // #ifdef APP-PLUS
84 // Android 13+ 需先取得通知权限,系统媒体通知才能显示
85 requestNotificationPermission()
86 // #endif
87
88 // 原生回调作为乐观更新的兜底同步(幂等,值相同不重复广播)
89 audio.onPlay(() => {
90 // 背景音频管理器设置新 src 后会自动开始播放,
91 // 若用户在 URL 加载期间已暂停(isPlay 被乐观置 false),在此立即纠正
92 if (!isPlay) {
93 audio.pause()
94 return
95 }
96 setPlayState(true)
97 })
98 audio.onPause(() => {
99 // 切歌期间旧音频的 onPause 回调不应影响播放状态
100 if (isHandlingEnded) return
101 setPlayState(false)
102 })
103 audio.onStop(() => {
104 // 切歌期间旧音频的 onStop 回调不应影响播放状态
105 if (isHandlingEnded) return
106 setPlayState(false)
107 })
108 audio.onEnded(() => {
109 handleEnded()
110 })
111 // 换源后(切换音质等)恢复播放进度
112 audio.onCanplay(() => {
113 if (pendingSeekTime != null) {
114 audio.seek(pendingSeekTime)
115 pendingSeekTime = null
116 }
117 })
118 audio.onError((err) => {
119 console.error('[player error]', err)
120 event.emit('playerError', err)
121 // 出错自动下一曲
122 playNext(true)
123 })
124 audio.onTimeUpdate(() => {
125 currentTime = audio.currentTime
126 duration = audio.duration
127 event.emit('playerProgressChanged', { currentTime, duration })
128 // 兜底检测播放完成(部分 Android 机型 onEnded 不触发)
129 if (duration > 0 && currentTime >= duration - 0.5 && isPlay && !isHandlingEnded) {
130 handleEnded()
131 }
132 // #ifdef APP-PLUS
133 // 节流同步播放进度到系统媒体会话(系统控件进度条)
134 if (Date.now() - mediaSyncAt > 1000) {
135 mediaSyncAt = Date.now()
136 updateMediaState({ isPlay, position: currentTime })
137 }
138 // #endif
139 })
140
141 // 恢复上次播放信息
142 restorePlayInfo()
143
144 // #ifdef APP-PLUS
145 // 注册 Android 系统媒体会话:蓝牙耳机线控 + 通知栏/锁屏媒体控件
146 // (DCloud Android 端音频实现不注册 MediaSession,需自行维护,见 media-session.js)
147 initMediaSession({
148 onPlay: () => play(),
149 onPause: () => pause(),
150 onNext: () => playNext(false),
151 onPrev: () => playPrev(),
152 })
153 // #endif
154}
155
156/**
157 * 同步系统媒体通知(通知栏/锁屏/控制中心)显示的歌曲信息。
158 * title 为背景音频管理器必填项,需在设置 src 之前调用。
159 */
160const updateMediaMeta = (musicInfo) => {
161 if (!audio || !musicInfo) return
162 audio.title = musicInfo.name || '未知歌曲'
163 audio.singer = musicInfo.singer || ''
164 if (musicInfo.album) audio.epname = musicInfo.album
165 if (musicInfo.img) audio.coverImgUrl = musicInfo.img
166}
167
168const restorePlayInfo = () => {
169 try {
170 const saved = uni.getStorageSync('starmusic_play_info')
171 if (saved && saved.musicInfo) {
172 playMusicInfo = { ...saved.musicInfo }
173 // 上次会话的播放地址是临时 CDN 链接,重启后基本已失效,
174 // 播放时会经 getMusicUrl 重新获取,这里直接丢弃避免误用
175 delete playMusicInfo.url
176 playList = saved.playList || []
177 playIndex = saved.playIndex || 0
178 currentTime = saved.time || 0
179 event.emit('playerMusicInfoChanged', { musicInfo: playMusicInfo, playList, playIndex })
180 }
181 } catch (e) {
182 console.log(e)
183 }
184}
185
186let savePlayInfoTimer = null
187
188/**
189 * 持久化播放状态(防抖合并)
190 * playNext/playPrev/playCurrent 每次切歌都会触发,playList 可能很大,
191 * 连续切歌时频繁全量 setStorageSync 会阻塞 UI 线程,合并为一次写入。
192 */
193const savePlayInfo = () => {
194 if (savePlayInfoTimer) return
195 savePlayInfoTimer = setTimeout(() => {
196 savePlayInfoTimer = null
197 try {
198 uni.setStorageSync('starmusic_play_info', {
199 musicInfo: playMusicInfo,
200 playList,
201 playIndex,
202 time: currentTime,
203 })
204 } catch (e) {}
205 }, 500)
206}
207
208// ============ 对外接口 ============
209
210/**
211 * 播放列表(设置播放列表并播放指定索引)
212 * @param {Array} list 音乐列表
213 * @param {number} index 播放索引
214 */
215export const playListByList = (list, index) => {
216 if (!list || !list.length) return
217 playList = [...list]
218 playIndex = index
219 playMusicInfo = list[index]
220 event.emit('playerMusicInfoChanged', { musicInfo: playMusicInfo, playList, playIndex })
221 playCurrent()
222}
223
224/**
225 * 播放单曲(加入当前列表或直接播放)
226 */
227export const playMusic = (musicInfo) => {
228 // 加入试听列表
229 const list = addListMusics(LIST_IDS.DEFAULT, [musicInfo], 'top')
230 playListByList(list, 0)
231}
232
233/** 播放当前歌曲(获取 URL 并播放) */
234const playCurrent = async () => {
235 if (!playMusicInfo) return
236 // 切歌时清掉上一首可能残留的换源 seek,避免作用于新歌
237 pendingSeekTime = null
238 // 点歌/切歌/自动下一曲都应当立即进入"播放中"状态(乐观更新)。
239 // URL 就绪后由 if (isPlay) safePlay() 真正开始播放;
240 // 若 URL 获取期间用户点了暂停(isPlay 被置 false),则不再自动播放。
241 setPlayState(true)
242 // 先清空上一首的歌词,避免新歌加载期间残留旧歌词
243 playLyricInfo = { lyric: '', tlyric: '' }
244 event.emit('playerLyricUpdated', playLyricInfo)
245 event.emit('playerGettingUrl')
246 try {
247 const requested = playMusicInfo
248 const info = await getMusicUrl({ musicInfo: playMusicInfo, isRefresh: false })
249 if (!info.url) throw new Error('获取播放地址失败')
250 if (info.fallbackFrom) {
251 // 多音源兜底成功:切换为备用源的歌曲条目(补 id 供列表/歌词/封面使用),并提示用户
252 playMusicInfo = normalizeMusicInfo(info)
253 uni.showToast({ title: `已切换至${SOURCE_NAMES[info.source] || info.source}播放`, icon: 'none', duration: 2000 })
254 event.emit('playerMusicInfoChanged', { musicInfo: playMusicInfo, playList, playIndex })
255 } else {
256 playMusicInfo = { ...requested, url: info.url }
257 }
258 // 先更新系统媒体通知信息再设置 src(title 必填)
259 updateMediaMeta(playMusicInfo)
260 audio.src = info.url
261 // URL 获取期间用户可能已点击暂停(isPlay 被乐观置 false),
262 // 背景音频管理器设置 src 会自动播放,此处立即暂停纠正
263 if (isPlay) safePlay()
264 else audio.pause()
265 savePlayInfo()
266
267 // 并行获取封面和歌词
268 getPicPath({ musicInfo: playMusicInfo })
269 .then((url) => {
270 playMusicInfo = { ...playMusicInfo, img: url || playMusicInfo.img }
271 event.emit('playerPicUpdated', url)
272 // 封面就绪后同步到系统媒体通知
273 if (url && audio) audio.coverImgUrl = url
274 })
275 .catch(() => {})
276
277 // 记录本次请求对应的歌曲,避免快速切歌时旧请求的结果覆盖新歌歌词
278 const lyricTargetId = playMusicInfo.id
279 getLyricInfo({ musicInfo: playMusicInfo })
280 .then((lyricInfo) => {
281 if (!playMusicInfo || playMusicInfo.id !== lyricTargetId) return
282 playLyricInfo = lyricInfo
283 event.emit('playerLyricUpdated', lyricInfo)
284 })
285 .catch((err) => {
286 if (!playMusicInfo || playMusicInfo.id !== lyricTargetId) return
287 console.log('[lyric]', err.message)
288 playLyricInfo = { lyric: '', tlyric: '' }
289 event.emit('playerLyricUpdated', playLyricInfo)
290 })
291 } catch (err) {
292 console.error('[playCurrent]', err.message)
293 // 播放失败时恢复状态,避免按钮停留在"播放中"
294 setPlayState(false)
295 event.emit('playerError', err)
296 uni.showToast({ title: err.message || '播放失败', icon: 'none' })
297 } finally {
298 // 释放播放结束处理重入锁
299 isHandlingEnded = false
300 }
301}
302
303/**
304 * 刷新当前歌曲的播放地址(用于切换音质等场景)
305 * - 按指定音质重新获取 URL 并替换播放源
306 * - 保持当前播放/暂停状态不变;正在播放时从原进度续播
307 * - 失败时回滚为原状态,不影响继续播放
308 * @param {object} param0
309 * @param {string} [param0.quality] 目标音质(不传则按当前设置)
310 * @param {boolean} [param0.isRefresh] 是否强制刷新(绕过 URL 内存缓存)
311 */
312export const refreshPlayUrl = async ({ quality, isRefresh = true } = {}) => {
313 if (!audio) initPlayer()
314 if (!playMusicInfo) return false
315 // 记录目标歌曲与当前状态,供异步期间校验与恢复
316 const targetId = playMusicInfo.id
317 const wasPlaying = isPlay
318 const resumeTime = currentTime
319 const oldUrl = playMusicInfo.url
320 const oldState = playMusicInfo
321
322 try {
323 const info = await getMusicUrl({ musicInfo: playMusicInfo, quality, isRefresh })
324 if (!info.url) throw new Error('获取播放地址失败')
325 // 换源期间用户可能已切歌,此时放弃本次结果
326 if (!playMusicInfo || playMusicInfo.id !== targetId) return false
327
328 if (info.fallbackFrom) {
329 // 多音源兜底成功:切换为备用源的歌曲条目并提示
330 playMusicInfo = normalizeMusicInfo(info)
331 uni.showToast({ title: `已切换至${SOURCE_NAMES[info.source] || info.source}播放`, icon: 'none', duration: 2000 })
332 } else {
333 playMusicInfo = { ...playMusicInfo, url: info.url, quality: info.quality }
334 }
335 updateMediaMeta(playMusicInfo)
336 audio.src = info.url
337 // 正在播放则续播:先 seek 到原进度(onCanplay 触发时执行);
338 // 原本处于暂停态时,需取消背景音频设置 src 引发的自动播放
339 if (wasPlaying) {
340 pendingSeekTime = resumeTime
341 safePlay()
342 } else {
343 audio.pause()
344 }
345 event.emit('playerMusicInfoChanged', { musicInfo: playMusicInfo, playList, playIndex })
346 savePlayInfo()
347 return true
348 } catch (err) {
349 console.error('[refreshPlayUrl]', err.message)
350 // 恢复原 URL,避免状态错乱
351 if (playMusicInfo && playMusicInfo.id === targetId) {
352 playMusicInfo = oldState
353 if (oldUrl) {
354 audio.src = oldUrl
355 if (wasPlaying) safePlay()
356 else audio.pause()
357 }
358 }
359 event.emit('playerError', err)
360 throw err
361 }
362}
363
364/**
365 * 乐观更新播放状态
366 * App 端 InnerAudioContext 的 onPause/onPlay 回调可能不触发或延迟触发,
367 * 若只依赖回调更新 isPlay,会出现"已暂停但按钮不变"。
368 * 因此调用原生方法的同时立即更新状态并广播,原生回调到达时再做幂等同步。
369 */
370const setPlayState = (playing) => {
371 if (isPlay === playing) return
372 isPlay = playing
373 event.emit('playerStateChanged', { isPlay })
374 // #ifdef APP-PLUS
375 // 同步到系统媒体会话(蓝牙线控/系统媒体控件的按钮状态)
376 updateMediaState({
377 isPlay,
378 position: currentTime,
379 title: playMusicInfo && playMusicInfo.name,
380 artist: playMusicInfo && playMusicInfo.singer,
381 album: playMusicInfo && playMusicInfo.album,
382 })
383 // #endif
384}
385
386/** 播放/暂停切换 */
387export const togglePlay = () => {
388 if (!audio) initPlayer()
389 if (!playMusicInfo) return
390 if (isPlay) {
391 setPlayState(false)
392 audio.pause()
393 } else {
394 setPlayState(true)
395 if (!audio.src && playMusicInfo) {
396 playCurrent()
397 } else {
398 safePlay()
399 }
400 }
401}
402
403/** 暂停 */
404export const pause = () => {
405 if (audio && isPlay) {
406 setPlayState(false)
407 audio.pause()
408 }
409}
410
411/** 播放 */
412export const play = () => {
413 if (!audio) initPlayer()
414 if (!isPlay && playMusicInfo) {
415 setPlayState(true)
416 if (!audio.src) playCurrent()
417 else safePlay()
418 }
419}
420
421/** 安全的 audio.play()(H5 端返回 Promise,可能因自动播放策略被拒绝) */
422const safePlay = () => {
423 try {
424 const p = audio.play()
425 if (p && typeof p.catch === 'function') p.catch(() => {})
426 } catch (e) {
427 console.log('[safePlay]', e)
428 }
429}
430
431/** 停止 */
432export const stop = () => {
433 if (audio) {
434 // 背景音频管理器不可将 src 置空(会触发 onError 导致自动切歌),仅 stop 即可
435 audio.stop()
436 }
437 // #ifdef APP-PLUS
438 stopMediaSession()
439 // #endif
440 setPlayState(false)
441}
442
443/** 处理播放结束 */
444const handleEnded = () => {
445 if (isHandlingEnded) return
446 isHandlingEnded = true
447 const mode = getSetting()['player.togglePlayMethod']
448 if (mode === 'singleLoop') {
449 // 单曲循环
450 audio.seek(0)
451 safePlay()
452 isHandlingEnded = false
453 return
454 }
455 playNext(true)
456}
457
458/** 计算下一首索引 */
459const getNextIndex = (isAuto = true) => {
460 if (!playList.length) return -1
461 const mode = getSetting()['player.togglePlayMethod']
462 let index = playIndex
463 switch (mode) {
464 case 'listLoop': // 列表循环
465 index = playIndex === playList.length - 1 ? 0 : playIndex + 1
466 break
467 case 'random': // 随机
468 index = getRandom(0, playList.length)
469 break
470 case 'list': // 顺序播放
471 index = playIndex === playList.length - 1 ? (isAuto ? -1 : 0) : playIndex + 1
472 break
473 case 'singleLoop': // 单曲循环
474 index = playIndex
475 break
476 default:
477 index = playIndex === playList.length - 1 ? 0 : playIndex + 1
478 }
479 return index
480}
481
482/** 计算上一首索引 */
483const getPrevIndex = () => {
484 if (!playList.length) return -1
485 const mode = getSetting()['player.togglePlayMethod']
486 let index = playIndex
487 switch (mode) {
488 case 'random':
489 index = getRandom(0, playList.length)
490 break
491 default:
492 index = playIndex === 0 ? playList.length - 1 : playIndex - 1
493 }
494 return index
495}
496
497/** 下一曲 */
498export const playNext = (isAuto = false) => {
499 const index = getNextIndex(isAuto)
500 if (index < 0) {
501 if (isAuto) {
502 // 顺序播放结束
503 setPlayState(false)
504 }
505 return
506 }
507 playIndex = index
508 playMusicInfo = playList[index]
509 currentTime = 0
510 duration = 0
511 event.emit('playerProgressChanged', { currentTime: 0, duration: 0 })
512 event.emit('playerMusicInfoChanged', { musicInfo: playMusicInfo, playList, playIndex })
513 playCurrent()
514}
515
516/** 上一曲 */
517export const playPrev = () => {
518 const index = getPrevIndex()
519 if (index < 0) return
520 playIndex = index
521 playMusicInfo = playList[index]
522 currentTime = 0
523 duration = 0
524 event.emit('playerProgressChanged', { currentTime: 0, duration: 0 })
525 event.emit('playerMusicInfoChanged', { musicInfo: playMusicInfo, playList, playIndex })
526 playCurrent()
527}
528
529/** 切换播放模式 */
530export const togglePlayMethod = () => {
531 const setting = getSetting()
532 const current = setting['player.togglePlayMethod']
533 const currentIndex = PLAY_MODE_LIST.indexOf(current)
534 const next = PLAY_MODE_LIST[(currentIndex + 1) % PLAY_MODE_LIST.length]
535 updateSetting({ 'player.togglePlayMethod': next })
536 event.emit('playMethodChanged', next)
537 return next
538}
539
540/** 设置播放模式 */
541export const setPlayMethod = (mode) => {
542 updateSetting({ 'player.togglePlayMethod': mode })
543 event.emit('playMethodChanged', mode)
544}
545
546/** 跳转进度 */
547export const seek = (time) => {
548 if (audio) {
549 audio.seek(time)
550 currentTime = time
551 }
552}
553
554/** 设置音量(背景音频管理器无音量属性,App 端音量由系统媒体音量控制,此接口保留兼容) */
555export const setVolume = (volume) => {
556 if (audio) audio.volume = volume
557}
558
559/** 设置倍速 */
560export const setPlaybackRate = (rate) => {
561 if (audio) audio.playbackRate = rate
562}
563
564// ============ 状态获取 ============
565export const getPlayState = () => ({
566 isPlay,
567 currentTime,
568 duration,
569 playMusicInfo,
570 playList,
571 playIndex,
572 lyricInfo: playLyricInfo,
573})
574
575/** 获取当前歌词(供播放页初始化读取) */
576export const getLyric = () => playLyricInfo
577
578/**
579 * 重新获取当前歌曲歌词(跳过缓存)
580 * 用于播放页首次进入时歌词为空的补偿,以及用户手动刷新
581 */
582export const refreshLyric = async (isRefresh = false) => {
583 if (!playMusicInfo) return { lyric: '', tlyric: '' }
584 const targetId = playMusicInfo.id
585 try {
586 const lyricInfo = await getLyricInfo({ musicInfo: playMusicInfo, isRefresh })
587 if (!playMusicInfo || playMusicInfo.id !== targetId) return playLyricInfo
588 playLyricInfo = lyricInfo
589 event.emit('playerLyricUpdated', lyricInfo)
590 return lyricInfo
591 } catch (err) {
592 console.log('[refreshLyric]', err.message)
593 return playLyricInfo
594 }
595}
596
597export const getIsPlay = () => isPlay
598export const getCurrentMusic = () => playMusicInfo
599export const getPlayList = () => [...playList]
600export const getPlayIndex = () => playIndex
601export const getCurrentTime = () => currentTime
602export const getDuration = () => duration
603
604/** 从某列表按索引播放(供列表页使用) */
605export const playListIndex = (list, index) => {
606 playListByList(list, index)
607}