原生js全局音乐播放

音乐图标自提
在这里插入图片描述
效果暂时(音乐没录进去)

音乐

2.新建script.js

//调用
const bgm = new BGMAutoPlayMgr('音乐地址'); //音乐
//开启音乐
bgm.toggleBGM();

function BGMAutoPlayMgr(url) {
	this.audioContext = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
	this.sourceNode = null;
	this.buffer = null;
	this.isPlayingBGM = false;
	this.toggleBGM = function () {
		if (typeof this.sourceNode == 'object') {
			if (this.isPlayingBGM) {
				this.sourceNode.stop();
				this.isPlayingBGM = false;
				$(".music").removeClass("music_rotate");
			} else {
				$(".music").addClass("music_rotate");
				this._playSourceNode();
			}
		}
	}
	this._playSourceNode = function () {
		const audioContext = this.audioContext;
		audioContext.resume();
		const _sourceNode = audioContext.createBufferSource();
		_sourceNode.buffer = this.buffer;
		_sourceNode.loop = true;
		_sourceNode.connect(audioContext.destination);
		_sourceNode.start(0);
		this.sourceNode = _sourceNode;
		this.isPlayingBGM = true;
		$(".music").addClass("music_rotate")
	}
	let loadAndAutoPlay = (audioUrl) => {
		const audioContext = this.audioContext;
		const xhr = new XMLHttpRequest();
		xhr.open('GET', audioUrl, true);
		xhr.responseType = 'arraybuffer';
		xhr.onreadystatechange = () => {
			if (xhr.status < 400 && xhr.status >= 200 && xhr.readyState === 4) {
				audioContext.decodeAudioData(xhr.response, buffer => {
					this.buffer = buffer;
					WeixinJSBridge.invoke("getNetworkType", {}, () => this._playSourceNode());
				});
			}
		}
		xhr.send();
	}
	loadAndAutoPlay(url);
	loadAndAutoPlay = null;
	let that = this;
	$(".music").on("click", function () {
		that.toggleBGM();
	})
}

新建index.html 引入script.js

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>全局音乐</title>
    <style>
    .music {
    position: absolute;
    width: .6rem;
    height: .6rem;
    z-index: 2;
    right: 3%;
    top: 6%;
}
.wid100 {
    width: 100%;
}
.music_rotate {
	-webkit-animation: rotate_music 5s linear infinite;
	transform-origin: 50% 50%;
}
@-webkit-keyframes rotate_music {
	0% {
		transform: rotate(0deg);
	}

	50% {
		transform: rotate(180deg);
	}

	100% {
		transform: rotate(360deg);
	}
}
    </style>
  </head>
  <body>
   <div class="music_rotate music">
      <img src="images/music_icon.png" class="wid100" alt="" />
    </div>
  </body>
  <script type="text/javascript">
  </script>
   <script src="js/script.js"></script>
</html>

如果需要点击按钮后暂停音乐播放,可直接调用bgm.toggleBGM();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值