-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwp-bg-music-player.js
More file actions
543 lines (464 loc) · 20.8 KB
/
Copy pathwp-bg-music-player.js
File metadata and controls
543 lines (464 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
/**
* WordPress Background Music Player - Compact Header Version
* 紧凑型页眉集成播放器
*/
(function() {
'use strict';
// 播放器配置 - 在WordPress后台通过PHP传递
const defaultConfig = {
playlist: [],
autoPlay: true,
volume: 0.7,
shuffle: false,
repeat: 'all' // 'all', 'one', 'none'
};
class WGMusicPlayer {
constructor(config) {
this.config = { ...defaultConfig, ...config };
this.playlist = this.config.playlist;
this.currentIndex = 0;
this.isPlaying = false;
this.audio = new Audio();
this.audio.volume = this.config.volume;
this.panelOpen = false;
// Session storage key for saving state
this.storageKey = 'wg_music_player_state';
this.init();
}
init() {
this.createPlayerHTML();
this.bindEvents();
// 尝试恢复播放状态
this.restoreState();
// 如果没有保存的状态,加载默认歌曲
if (this.audio.src === '' && this.playlist.length > 0) {
this.loadTrack(this.currentIndex);
// 尝试自动播放
if (this.config.autoPlay) {
this.play();
}
}
// 页面卸载前保存状态
window.addEventListener('beforeunload', () => this.saveState());
}
/**
* 保存播放状态到 sessionStorage
*/
saveState() {
const state = {
currentIndex: this.currentIndex,
currentTime: this.audio.currentTime || 0,
isPlaying: this.isPlaying,
volume: this.audio.volume
};
sessionStorage.setItem(this.storageKey, JSON.stringify(state));
}
/**
* 从 sessionStorage 恢复播放状态
*/
restoreState() {
try {
const savedState = sessionStorage.getItem(this.storageKey);
if (!savedState) return;
const state = JSON.parse(savedState);
// 恢复索引
if (state.currentIndex >= 0 && state.currentIndex < this.playlist.length) {
this.currentIndex = state.currentIndex;
}
// 加载歌曲
this.loadTrack(this.currentIndex, false); // false = 不重置播放状态
// 恢复播放位置
if (state.currentTime > 0) {
this.audio.currentTime = state.currentTime;
}
// 恢复音量
if (state.volume > 0) {
this.audio.volume = state.volume;
}
// 尝试恢复播放状态(如果之前在播放)
if (state.isPlaying) {
// 之前在播放,尝试继续播放
this.audio.play().then(() => {
this.isPlaying = true;
this.updatePlayButton();
}).catch(() => {
// 浏览器阻止自动播放
console.log('Auto-play prevented by browser, click to resume');
this.isPlaying = false;
this.updatePlayButton();
});
}
} catch (e) {
console.error('Failed to restore player state:', e);
}
}
createPlayerHTML() {
// 找到或创建header player容器
let headerContainer = document.querySelector('.wg-header-player');
if (!headerContainer) {
// Twenty Eleven主题的结构:#branding > nav
const header = document.querySelector('#branding') || document.querySelector('header') || document.querySelector('.site-header');
if (header) {
headerContainer = document.createElement('div');
headerContainer.className = 'wg-header-player';
// 找到nav导航区域,将播放器追加到最后(最右边)
const nav = header.querySelector('nav');
if (nav) {
// 设置nav为flex布局,让播放器靠右
nav.style.display = 'flex';
nav.style.alignItems = 'center';
nav.style.justifyContent = 'space-between';
nav.appendChild(headerContainer);
} else {
header.appendChild(headerContainer);
}
}
}
if (!headerContainer) {
console.warn('WG Music Player: Could not find header element');
return;
}
// 创建紧凑型播放器 - 新的元素顺序
const toggleHTML = `
<div class="wg-player-toggle">
<!-- 歌曲名称 -->
<span class="wg-track-name">加载中...</span>
<!-- 播放/暂停按钮 -->
<button class="wg-play-btn" title="播放/暂停">
<svg class="icon-play" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
<svg class="icon-pause" style="display:none" viewBox="0 0 24 24"><path d="M6 20h4V4H6v16zm8-16v16h4V4h-4z"/></svg>
</button>
<!-- 歌单按钮 -->
<button class="wg-playlist-btn" title="播放列表">
<svg viewBox="0 0 24 24"><path d="M15 6H3v2h12V6zm0 4H3v2h12v-2zM3 16h8v-2H3v2zM17 6v8.18c-.31-.11-.65-.18-1-.18-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3V8h3V6h-5z"/></svg>
</button>
<!-- 音量按钮 -->
<button class="wg-volume-btn" title="音量">
<!-- 正常音量:直角三角形 -->
<svg class="volume-on" viewBox="0 0 24 24"><path d="M3 9v6h4l7 5V4l-7 5H3z"/></svg>
<!-- 静音:带斜线 -->
<svg class="volume-off" style="display:none" viewBox="0 0 24 24"><path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z"/></svg>
</button>
<!-- 音量滑块 -->
<div class="wg-volume-slider">
<div class="wg-volume-current" style="width: 70%"></div>
</div>
</div>
`;
// 创建播放器面板
const panelHTML = `
<div class="wg-player-panel">
<!-- 当前歌曲 -->
<div class="wg-panel-header">
<div class="wg-now-playing-title">加载中...</div>
<div class="wg-now-playing-artist">请稍候</div>
</div>
<!-- 进度条 -->
<div class="wg-progress-section">
<div class="wg-progress-bar">
<div class="wg-progress-current" style="width: 0%"></div>
</div>
<div class="wg-progress-times">
<span class="wg-current-time">0:00</span>
<span class="wg-total-time">0:00</span>
</div>
</div>
<!-- 播放列表 -->
<div class="wg-playlist-items"></div>
</div>
`;
headerContainer.innerHTML = toggleHTML + panelHTML;
// 存储元素引用
this.elements = {
container: headerContainer,
toggle: headerContainer.querySelector('.wg-player-toggle'),
trackName: headerContainer.querySelector('.wg-track-name'),
playBtn: headerContainer.querySelector('.wg-play-btn'),
volumeBtn: headerContainer.querySelector('.wg-volume-btn'),
volumeSlider: headerContainer.querySelector('.wg-volume-slider'),
volumeCurrent: headerContainer.querySelector('.wg-volume-current'),
playlistBtn: headerContainer.querySelector('.wg-playlist-btn'),
panel: headerContainer.querySelector('.wg-player-panel'),
nowPlayingTitle: headerContainer.querySelector('.wg-now-playing-title'),
nowPlayingArtist: headerContainer.querySelector('.wg-now-playing-artist'),
progressBar: headerContainer.querySelector('.wg-progress-bar'),
progressCurrent: headerContainer.querySelector('.wg-progress-current'),
currentTime: headerContainer.querySelector('.wg-current-time'),
totalTime: headerContainer.querySelector('.wg-total-time'),
playlistItems: headerContainer.querySelector('.wg-playlist-items')
};
this.renderPlaylist();
}
renderPlaylist() {
this.elements.playlistItems.innerHTML = this.playlist.map((track, index) => `
<div class="wg-playlist-item" data-index="${index}">
<div class="wg-playlist-item-title">${this.escapeHtml(track.title)}</div>
<div class="wg-playlist-item-duration">${track.duration || ''}</div>
<div class="wg-playlist-item-playing">
<span></span><span></span><span></span>
</div>
</div>
`).join('');
}
bindEvents() {
// 播放按钮点击
this.elements.playBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.togglePlay();
});
// 歌单按钮点击
this.elements.playlistBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.elements.panel.classList.toggle('show');
});
// 音量控制
this.elements.volumeBtn.addEventListener('click', (e) => {
e.stopPropagation();
this.toggleMute();
});
this.elements.volumeSlider.addEventListener('click', (e) => {
e.stopPropagation();
const rect = this.elements.volumeSlider.getBoundingClientRect();
const percent = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
this.setVolume(percent);
});
// 音量滑块拖动支持
let isDraggingVolume = false;
this.elements.volumeSlider.addEventListener('mousedown', (e) => {
isDraggingVolume = true;
e.stopPropagation();
});
document.addEventListener('mousemove', (e) => {
if (!isDraggingVolume) return;
const rect = this.elements.volumeSlider.getBoundingClientRect();
const percent = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
this.setVolume(percent);
});
document.addEventListener('mouseup', () => {
isDraggingVolume = false;
});
// 进度条
this.elements.progressBar.addEventListener('click', (e) => {
const rect = this.elements.progressBar.getBoundingClientRect();
const percent = (e.clientX - rect.left) / rect.width;
this.seekTo(percent);
});
// 播放列表项点击
this.elements.playlistItems.addEventListener('click', (e) => {
const item = e.target.closest('.wg-playlist-item');
if (item) {
const index = parseInt(item.dataset.index);
this.playTrack(index);
}
});
// 点击面板外部关闭面板
document.addEventListener('click', (e) => {
if (this.panelOpen && !this.elements.container.contains(e.target)) {
this.closePanel();
}
});
// 音频事件
this.audio.addEventListener('timeupdate', () => this.updateProgress());
this.audio.addEventListener('ended', () => this.onTrackEnd());
this.audio.addEventListener('loadedmetadata', () => {
this.elements.totalTime.textContent = this.formatTime(this.audio.duration);
});
this.audio.addEventListener('error', () => {
console.error('Audio load error');
this.playNext();
});
// 键盘快捷键
document.addEventListener('keydown', (e) => {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
switch(e.code) {
case 'Space':
e.preventDefault();
this.togglePlay();
break;
case 'ArrowLeft':
e.preventDefault();
this.playPrevious();
break;
case 'ArrowRight':
e.preventDefault();
this.playNext();
break;
}
});
}
togglePanel() {
this.panelOpen = !this.panelOpen;
this.elements.panel.classList.toggle('show', this.panelOpen);
}
closePanel() {
this.panelOpen = false;
this.elements.panel.classList.remove('show');
}
loadTrack(index, resetState = true) {
if (!this.playlist[index]) return;
const track = this.playlist[index];
this.currentIndex = index;
// 只在需要时重置音频源(恢复状态时保持当前进度)
if (resetState || this.audio.src !== track.url) {
this.audio.src = track.url;
}
// 更新紧凑按钮 - 只显示歌曲名称
this.elements.trackName.textContent = track.title;
// 更新面板
this.elements.nowPlayingTitle.textContent = track.title;
this.elements.nowPlayingArtist.textContent = track.artist;
// 更新播放列表高亮
document.querySelectorAll('.wg-playlist-item').forEach((item, i) => {
item.classList.toggle('active', i === index);
const playingEl = item.querySelector('.wg-playlist-item-playing');
if (playingEl) {
playingEl.style.display = i === index && this.isPlaying ? 'flex' : 'none';
}
});
// 保存状态
this.saveState();
}
play() {
this.audio.play().then(() => {
this.isPlaying = true;
this.updatePlayButton();
this.saveState(); // 保存播放状态
}).catch(err => {
console.log('Auto-play prevented:', err);
this.isPlaying = false;
this.updatePlayButton();
});
}
pause() {
this.audio.pause();
this.isPlaying = false;
this.updatePlayButton();
this.saveState(); // 保存播放状态
}
togglePlay() {
this.isPlaying ? this.pause() : this.play();
this.updatePlaylistAnimation();
}
updatePlayButton() {
// 更新播放按钮图标
const iconPlay = this.elements.playBtn.querySelector('.icon-play');
const iconPause = this.elements.playBtn.querySelector('.icon-pause');
iconPlay.style.display = this.isPlaying ? 'none' : 'block';
iconPause.style.display = this.isPlaying ? 'block' : 'none';
}
updatePlaylistAnimation() {
const activeItem = this.elements.playlistItems.querySelector('.wg-playlist-item.active');
if (activeItem) {
activeItem.querySelector('.wg-playlist-item-playing').style.display = this.isPlaying ? 'flex' : 'none';
}
}
playTrack(index) {
this.loadTrack(index);
this.play();
}
playNext() {
let nextIndex;
if (this.config.shuffle) {
nextIndex = Math.floor(Math.random() * this.playlist.length);
} else {
nextIndex = (this.currentIndex + 1) % this.playlist.length;
}
this.loadTrack(nextIndex);
this.play();
}
playPrevious() {
const prevIndex = (this.currentIndex - 1 + this.playlist.length) % this.playlist.length;
this.loadTrack(prevIndex);
this.play();
}
onTrackEnd() {
switch(this.config.repeat) {
case 'one':
this.audio.currentTime = 0;
this.play();
break;
case 'none':
if (this.currentIndex < this.playlist.length - 1) {
this.playNext();
} else {
this.pause();
}
break;
default:
this.playNext();
}
}
toggleMode() {
const modes = ['all', 'one', 'shuffle'];
const currentModeIndex = modes.indexOf(this.config.shuffle ? 'shuffle' : this.config.repeat);
const nextMode = modes[(currentModeIndex + 1) % modes.length];
if (nextMode === 'shuffle') {
this.config.shuffle = true;
} else {
this.config.shuffle = false;
this.config.repeat = nextMode;
}
// 更新图标
this.elements.modeBtn.querySelector('.mode-all').style.display = nextMode === 'all' ? 'block' : 'none';
this.elements.modeBtn.querySelector('.mode-one').style.display = nextMode === 'one' ? 'block' : 'none';
this.elements.modeBtn.querySelector('.mode-shuffle').style.display = nextMode === 'shuffle' ? 'block' : 'none';
// 更新激活状态
this.elements.modeBtn.classList.toggle('active', nextMode !== 'all');
}
updateProgress() {
if (!this.audio.duration) return;
const percent = (this.audio.currentTime / this.audio.duration) * 100;
this.elements.progressCurrent.style.width = percent + '%';
this.elements.currentTime.textContent = this.formatTime(this.audio.currentTime);
// 节流保存:每1秒保存一次进度
if (!this.lastSaveTime || Date.now() - this.lastSaveTime > 1000) {
this.saveState();
this.lastSaveTime = Date.now();
}
}
seekTo(percent) {
if (!this.audio.duration) return;
this.audio.currentTime = percent * this.audio.duration;
this.saveState(); // 拖动进度条后保存状态
}
setVolume(volume) {
this.audio.volume = Math.max(0, Math.min(1, volume));
this.elements.volumeCurrent.style.width = (this.audio.volume * 100) + '%';
this.updateVolumeIcon();
}
toggleMute() {
if (this.audio.volume > 0) {
this.previousVolume = this.audio.volume;
this.setVolume(0);
} else {
this.setVolume(this.previousVolume || 0.7);
}
}
updateVolumeIcon() {
const volumeOn = this.elements.volumeBtn.querySelector('.volume-on');
const volumeOff = this.elements.volumeBtn.querySelector('.volume-off');
if (this.audio.volume === 0) {
volumeOn.style.display = 'none';
volumeOff.style.display = 'block';
} else {
volumeOn.style.display = 'block';
volumeOff.style.display = 'none';
}
}
formatTime(seconds) {
if (isNaN(seconds)) return '0:00';
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return mins + ':' + (secs < 10 ? '0' : '') + secs;
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
}
// 从WordPress获取配置并初始化
if (typeof wgMusicPlayerConfig !== 'undefined') {
new WGMusicPlayer(wgMusicPlayerConfig);
}
})();