以下代码写入主题 js 文件:
if (document.getElementById("music")) {
(function() {
var a = document.getElementById("audio");
var b = document.getElementById("music");
var c = a.getAttribute("data-src").split(",");
var d = a.getAttribute("data-vol");
if (d && d >= 0 && d <= 1) {
a.volume = d
}
a.src = c.shift();
a.addEventListener('play', g);
a.addEventListener('pause', h);
a.addEventListener('ended', f);
a.addEventListener('error', f);
a.addEventListener('canplay', j);
function f() {
if (!c.length) {
a.removeEventListener('play', g);
a.removeEventListener('pause', h);
a.removeEventListener('ended', f);
a.removeEventListener('error', f);
a.removeEventListener('canplay', j);
b.style.display = "none";
alert("本站的背景音乐好像有问题了,希望您可以通过留言等方式通知管理员,谢谢您的帮助。")
} else {
a.src = c.shift();
a.play()
}
}
function g() {
b.setAttribute("class", "play")
}
function h() {
b.removeAttribute("class")
}
function j() {
c.push(a.src)
}
b.onclick = function() {
if (a.canPlayType('audio/mpeg') != "" || a.canPlayType('audio/ogg;codes="vorbis"') != "" || a.canPlayType('audio/mp4;codes="mp4a.40.5"') != "") {
if (a.paused) {
if (a.error) {
f()
} else {
a.play()
}
} else {
a.pause()
}
} else {
alert("对不起,您的浏览器不支持HTML5音频播放,请升级您的浏览器。")
}
};
b.removeAttribute("class")
})()
}
var cornertool = true;
以下代码写入主题 functions.php 文件,用于后台添加音乐。
function themeConfig($form) {
$MusicSet = new Typecho_Widget_Helper_Form_Element_Radio('MusicSet',
array('order' => _t('顺序播放'),
'shuffle' => _t('随机播放'),
0 => _t('关闭')),
0, _t('背景音乐'));
$form->addInput($MusicSet);
$MusicUrl = new Typecho_Widget_Helper_Form_Element_Textarea('MusicUrl', NULL, NULL, _t('背景音乐地址'));
$form->addInput($MusicUrl);
$MusicVol = new Typecho_Widget_Helper_Form_Element_Text('MusicVol', NULL, NULL, _t('背景音乐播放音量(输入范围:0~1)'));
$form->addInput($MusicVol->addRule('isInteger', _t('请填入一个0~1内的数字')));
}
同样,以下代码写入主题 functions.php 文件:
function Playlist() {
$options = Helper::options();
$arr = explode(PHP_EOL, $options->MusicUrl);
if ($options->MusicSet == 'shuffle') {shuffle($arr);}echo implode(',', $arr);
}
以下代码写入主题 footer.php 文件:
<div class="setting_tool">
<div id="music"><audio id="audio" data-src="<?php Playlist() ?>"<?php if ($this->options->MusicVol): ?> data-vol="<?php $this->options->MusicVol(); ?>"<?php endif; ?> preload="none"></audio></div>
</div>
以下代码写入主题 css 文件:
.setting_tool{position:fixed;bottom:18%;right:0;background:rgb(217 217 217 / 50%);cursor:pointer;color:#333;width:30px;line-height:30px;text-align:center}
#music:before{content:"音乐图标"}
#music.play:before{content:"播放中图标"}