Repository navigation
Expand file tree
/
Copy pathwp-bg-music-player.php
More file actions
570 lines (496 loc) · 23.1 KB
/
Copy pathwp-bg-music-player.php
File metadata and controls
570 lines (496 loc) · 23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
<?php
/**
* Plugin Name: Winggon Background Music Player
* Plugin URI: https://winggon.cc
* Description: 紧凑型页眉集成音乐播放器,支持播放列表管理、自动播放、音量控制等功能
* Version: 1.0.1
* Author: Winggon
* Author URI: https://winggon.cc
* License: GPL v2 or later
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
class WG_Music_Player {
private static $instance = null;
private $option_name = 'wg_music_player_settings';
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
// 初始化钩子
add_action('wp_enqueue_scripts', array($this, 'enqueue_assets'));
add_action('wp_footer', array($this, 'render_player'));
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
add_action('wp_ajax_wg_upload_music', array($this, 'ajax_upload_music'));
add_action('wp_ajax_wg_delete_music', array($this, 'ajax_delete_music'));
add_action('wp_ajax_wg_update_playlist', array($this, 'ajax_update_playlist'));
}
/**
* 加载CSS和JS文件
*/
public function enqueue_assets() {
// 只在前端加载
if (is_admin()) return;
// 获取插件目录URL
$plugin_url = plugin_dir_url(__FILE__);
// 加载CSS
wp_enqueue_style('wg-music-player-style', $plugin_url . 'wp-bg-music-player.css', array(), '1.0.0');
// 加载JS
wp_enqueue_script('wg-music-player-script', $plugin_url . 'wp-bg-music-player.js', array(), '1.0.0', true);
// 传递配置到JS
$settings = $this->get_settings();
wp_localize_script('wg-music-player-script', 'wgMusicPlayerConfig', array(
'playlist' => $settings['playlist'],
'autoPlay' => $settings['auto_play'] === '1',
'volume' => floatval($settings['volume']),
'shuffle' => $settings['shuffle'] === '1',
'repeat' => $settings['repeat_mode']
));
}
/**
* 加载后台脚本(媒体库)
*/
public function enqueue_admin_scripts($hook) {
// 只在设置页面加载
if ('settings_page_wg-music-player' !== $hook) {
return;
}
// 加载WordPress媒体库
wp_enqueue_media();
}
/**
* 在页面底部渲染播放器
*/
public function render_player() {
// 检查是否启用播放器
$settings = $this->get_settings();
if (empty($settings['playlist']) || $settings['enabled'] !== '1') {
return;
}
// 播放器HTML由JavaScript生成,这里只需确保JS已加载
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_options_page(
'背景音乐播放器',
'背景音乐',
'manage_options',
'wg-music-player',
array($this, 'render_admin_page')
);
}
/**
* 注册设置
*/
public function register_settings() {
register_setting('wg_music_player_settings', $this->option_name, array(
'sanitize_callback' => array($this, 'sanitize_settings')
));
}
/**
* 清理设置数据
*/
public function sanitize_settings($input) {
$sanitized = array();
$sanitized['enabled'] = isset($input['enabled']) ? '1' : '0';
$sanitized['auto_play'] = isset($input['auto_play']) ? '1' : '0';
$sanitized['shuffle'] = isset($input['shuffle']) ? '1' : '0';
$sanitized['volume'] = isset($input['volume']) ? floatval($input['volume']) : 0.7;
$sanitized['repeat_mode'] = isset($input['repeat_mode']) ? sanitize_text_field($input['repeat_mode']) : 'all';
// 解析播放列表JSON数据
if (isset($input['playlist']) && is_string($input['playlist'])) {
$playlist_data = json_decode($input['playlist'], true);
$sanitized['playlist'] = is_array($playlist_data) ? $this->sanitize_playlist($playlist_data) : array();
} elseif (isset($input['playlist']) && is_array($input['playlist'])) {
$sanitized['playlist'] = $this->sanitize_playlist($input['playlist']);
} else {
$sanitized['playlist'] = array();
}
return $sanitized;
}
/**
* 清理播放列表数据
*/
private function sanitize_playlist($playlist) {
if (!is_array($playlist)) return array();
return array_map(function($item) {
return array(
'title' => sanitize_text_field($item['title']),
'artist' => sanitize_text_field($item['artist']),
'url' => esc_url_raw($item['url']),
'cover' => isset($item['cover']) ? esc_url_raw($item['cover']) : '',
'duration' => sanitize_text_field($item['duration'])
);
}, $playlist);
}
/**
* 获取设置
*/
private function get_settings() {
$defaults = array(
'enabled' => '1',
'auto_play' => '1',
'shuffle' => '0',
'volume' => '0.7',
'repeat_mode' => 'all',
'playlist' => array()
);
$settings = get_option($this->option_name, array());
return wp_parse_args($settings, $defaults);
}
/**
* AJAX: 上传音乐文件
*/
public function ajax_upload_music() {
check_ajax_referer('wg_music_player_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => '权限不足'));
}
if (empty($_FILES['file'])) {
wp_send_json_error(array('message' => '没有上传文件'));
}
$file = $_FILES['file'];
// 验证文件类型
$allowed_types = array('audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/m4a');
if (!in_array($file['type'], $allowed_types)) {
wp_send_json_error(array('message' => '不支持的文件格式'));
}
// 上传到WordPress媒体库
$upload = wp_handle_upload($file, array('test_form' => false));
if (isset($upload['error'])) {
wp_send_json_error(array('message' => $upload['error']));
}
// 获取文件信息
$title = pathinfo($file['name'], PATHINFO_FILENAME);
$duration = $this->get_audio_duration($upload['file']);
wp_send_json_success(array(
'url' => $upload['url'],
'title' => $title,
'duration' => $duration
));
}
/**
* AJAX: 删除音乐
*/
public function ajax_delete_music() {
check_ajax_referer('wg_music_player_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => '权限不足'));
}
$index = isset($_POST['index']) ? intval($_POST['index']) : -1;
$settings = $this->get_settings();
if (isset($settings['playlist'][$index])) {
array_splice($settings['playlist'], $index, 1);
update_option($this->option_name, $settings);
wp_send_json_success();
}
wp_send_json_error(array('message' => '删除失败'));
}
/**
* AJAX: 更新播放列表
*/
public function ajax_update_playlist() {
check_ajax_referer('wg_music_player_nonce', 'nonce');
if (!current_user_can('manage_options')) {
wp_send_json_error(array('message' => '权限不足'));
}
$playlist = isset($_POST['playlist']) ? json_decode(stripslashes($_POST['playlist']), true) : array();
$settings = $this->get_settings();
$settings['playlist'] = $this->sanitize_playlist($playlist);
update_option($this->option_name, $settings);
wp_send_json_success();
}
/**
* 获取音频时长
*/
private function get_audio_duration($file_path) {
if (!file_exists($file_path)) return '0:00';
// 尝试使用getID3(如果已安装)
if (class_exists('getID3')) {
$getID3 = new getID3();
$info = $getID3->analyze($file_path);
if (isset($info['playtime_string'])) {
return $info['playtime_string'];
}
}
// 简单估算(基于文件大小)
$file_size = filesize($file_path);
$estimated_bitrate = 128; // kbps
$estimated_duration = ($file_size * 8) / ($estimated_bitrate * 1000);
$minutes = floor($estimated_duration / 60);
$seconds = floor($estimated_duration % 60);
return $minutes . ':' . str_pad($seconds, 2, '0', STR_PAD_LEFT);
}
/**
* 渲染管理页面
*/
public function render_admin_page() {
$settings = $this->get_settings();
?>
<div class="wrap">
<h1>🎵 背景音乐播放器设置</h1>
<div id="wg-music-player-admin">
<form method="post" action="options.php">
<?php settings_fields('wg_music_player_settings'); ?>
<!-- 基本设置 -->
<div class="wg-admin-section">
<h2 class="wg-section-title">基本设置</h2>
<table class="form-table">
<tr>
<th scope="row">启用播放器</th>
<td>
<label>
<input type="checkbox" name="<?php echo esc_attr($this->option_name); ?>[enabled]" value="1" <?php checked($settings['enabled'], '1'); ?>>
在网站前端显示播放器
</label>
</td>
</tr>
<tr>
<th scope="row">自动播放</th>
<td>
<label>
<input type="checkbox" name="<?php echo esc_attr($this->option_name); ?>[auto_play]" value="1" <?php checked($settings['auto_play'], '1'); ?>>
页面加载后自动播放音乐
<p class="description">注意:现代浏览器可能会阻止自动播放</p>
</label>
</td>
</tr>
<tr>
<th scope="row">默认音量</th>
<td>
<input type="range" name="<?php echo esc_attr($this->option_name); ?>[volume]" value="<?php echo esc_attr($settings['volume']); ?>" min="0" max="1" step="0.1" id="wg-volume-setting">
<span id="wg-volume-value"><?php echo round($settings['volume'] * 100); ?>%</span>
</td>
</tr>
<tr>
<th scope="row">播放模式</th>
<td>
<select name="<?php echo esc_attr($this->option_name); ?>[repeat_mode]">
<option value="all" <?php selected($settings['repeat_mode'], 'all'); ?>>列表循环</option>
<option value="one" <?php selected($settings['repeat_mode'], 'one'); ?>>单曲循环</option>
<option value="none" <?php selected($settings['repeat_mode'], 'none'); ?>>播放一次</option>
</select>
</td>
</tr>
<tr>
<th scope="row">随机播放</th>
<td>
<label>
<input type="checkbox" name="<?php echo esc_attr($this->option_name); ?>[shuffle]" value="1" <?php checked($settings['shuffle'], '1'); ?>>
随机播放列表中的歌曲
</label>
</td>
</tr>
</table>
</div>
<!-- 播放列表管理 -->
<div class="wg-admin-section">
<h2 class="wg-section-title">播放列表管理</h2>
<div class="wg-playlist-actions">
<button type="button" class="button wg-add-from-media">从媒体库添加</button>
<button type="button" class="button wg-upload-music">上传新音乐</button>
<input type="file" id="wg-music-upload" accept="audio/*" style="display:none;">
</div>
<table class="wp-list-table widefat fixed striped">
<thead>
<tr>
<th style="width:50px;"></th>
<th>歌曲名称</th>
<th>歌手</th>
<th>时长</th>
<th style="width:80px;">操作</th>
</tr>
</thead>
<tbody id="wg-playlist-tbody">
<?php foreach ($settings['playlist'] as $index => $track) : ?>
<tr data-index="<?php echo $index; ?>">
<td class="wg-drag-handle">☰</td>
<td>
<input type="text" class="wg-track-title" value="<?php echo esc_attr($track['title']); ?>" placeholder="歌曲名称">
<input type="hidden" class="wg-track-url" value="<?php echo esc_attr($track['url']); ?>">
</td>
<td>
<input type="text" class="wg-track-artist" value="<?php echo esc_attr($track['artist']); ?>" placeholder="歌手">
</td>
<td>
<input type="text" class="wg-track-duration" value="<?php echo esc_attr($track['duration']); ?>" placeholder="0:00">
</td>
<td>
<button type="button" class="button wg-delete-track">删除</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<input type="hidden" name="<?php echo esc_attr($this->option_name); ?>[playlist]" id="wg-playlist-data" value=''>
</div>
<?php submit_button('保存设置'); ?>
</form>
</div>
<style>
#wg-music-player-admin { max-width: 900px; margin-top: 20px; }
.wg-admin-section { background: #fff; padding: 20px; margin-bottom: 20px; border: 1px solid #ccc; box-shadow: 0 1px 1px rgba(0,0,0,.04); }
.wg-section-title { margin-top: 0; padding-bottom: 10px; border-bottom: 1px solid #eee; }
.wg-playlist-actions { margin-bottom: 15px; }
.wg-playlist-actions button { margin-right: 10px; }
.wg-drag-handle { cursor: move; text-align: center; color: #999; }
.wg-drag-handle:hover { color: #333; }
#wg-playlist-tbody input[type="text"] { width: 100%; }
#wg-volume-setting { width: 200px; vertical-align: middle; }
</style>
<script>
jQuery(document).ready(function($) {
'use strict';
// 检查 wp.media 是否可用
if (typeof wp === 'undefined' || !wp.media) {
console.error('WordPress media library not loaded');
$('.wg-add-from-media').hide();
return;
}
// 音量滑块
$('#wg-volume-setting').on('input', function() {
$('#wg-volume-value').text(Math.round($(this).val() * 100) + '%');
});
// 媒体库选择器
$('.wg-add-from-media').on('click', function(e) {
e.preventDefault();
console.log('Opening media library...');
var frame = wp.media({
title: '选择音乐文件',
multiple: false,
library: { type: 'audio' },
button: { text: '添加到播放列表' }
});
frame.on('select', function() {
var attachment = frame.state().get('selection').first().toJSON();
console.log('Selected:', attachment);
addTrackToPlaylist(attachment.url, attachment.title, '', '');
});
frame.open();
});
// 上传新音乐
$('.wg-upload-music').on('click', function(e) {
e.preventDefault();
$('#wg-music-upload').click();
});
$('#wg-music-upload').on('change', function() {
var file = this.files[0];
if (!file) return;
var formData = new FormData();
formData.append('file', file);
formData.append('action', 'wg_upload_music');
formData.append('nonce', '<?php echo wp_create_nonce('wg_music_player_nonce'); ?>');
$.ajax({
url: ajaxurl,
type: 'POST',
data: formData,
processData: false,
contentType: false,
beforeSend: function() {
$('.wg-upload-music').text('上传中...');
},
success: function(response) {
if (response.success) {
addTrackToPlaylist(response.data.url, response.data.title, '', response.data.duration);
} else {
alert('上传失败: ' + response.data.message);
}
},
complete: function() {
$('.wg-upload-music').text('上传新音乐');
$('#wg-music-upload').val('');
}
});
});
// 添加歌曲到播放列表
function addTrackToPlaylist(url, title, artist, duration) {
var index = $('#wg-playlist-tbody tr').length;
var html = `
<tr data-index="${index}">
<td class="wg-drag-handle">☰</td>
<td>
<input type="text" class="wg-track-title" value="${title}" placeholder="歌曲名称">
<input type="hidden" class="wg-track-url" value="${url}">
</td>
<td>
<input type="text" class="wg-track-artist" value="${artist}" placeholder="歌手">
</td>
<td>
<input type="text" class="wg-track-duration" value="${duration}" placeholder="0:00">
</td>
<td>
<button type="button" class="button wg-delete-track">删除</button>
</td>
</tr>
`;
$('#wg-playlist-tbody').append(html);
}
// 删除歌曲
$(document).on('click', '.wg-delete-track', function() {
if (confirm('确定要删除这首歌曲吗?')) {
$(this).closest('tr').remove();
updatePlaylistIndexes();
}
});
// 更新索引
function updatePlaylistIndexes() {
$('#wg-playlist-tbody tr').each(function(i) {
$(this).attr('data-index', i);
});
}
// 表格排序
$('#wg-playlist-tbody').sortable({
handle: '.wg-drag-handle',
axis: 'y',
stop: function() {
updatePlaylistIndexes();
}
});
// 保存前序列化播放列表
$('form').on('submit', function() {
var playlist = [];
$('#wg-playlist-tbody tr').each(function() {
var $row = $(this);
playlist.push({
title: $row.find('.wg-track-title').val(),
artist: $row.find('.wg-track-artist').val(),
url: $row.find('.wg-track-url').val(),
duration: $row.find('.wg-track-duration').val(),
cover: ''
});
});
$('#wg-playlist-data').val(JSON.stringify(playlist));
console.log('Playlist saved:', playlist);
});
});
</script>
</div>
<?php
}
}
// 初始化插件
function wg_music_player_init() {
return WG_Music_Player::get_instance();
}
add_action('plugins_loaded', 'wg_music_player_init');
// 激活插件时的操作
register_activation_hook(__FILE__, function() {
$default = array(
'enabled' => '1',
'auto_play' => '1',
'shuffle' => '0',
'volume' => '0.7',
'repeat_mode' => 'all',
'playlist' => array()
);
add_option('wg_music_player_settings', $default);
});