点击上方 蓝字关注我们
本偏文章转载于https://www.cnblogs.com/coderDemo/p/14105323.html
感谢这位前端大佬提供技术支持~~~
##### 本篇文章讲的是基于vue框架下使用的,在其他框架使用也一样,没有什么差别,只需要根据自己的框架来修改就好啦~~~
### 1。在共同目录下封装一个JS代码,是用调用播放音乐的,代码如下
class Music { constructor(url, loop) { const AudioCtx = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext this.context = new AudioCtx this.url = url this.handle = {} this.loop = loop || false this.source = null this.audioBuffer = null this.loadMusic() } stop() { if (this.source) { this.source.stop() this.source.playStatus = 1 } } // 0 初始化完成未播放 1 已暂停 2 正在播放 play() { if (this.source) { switch (this.source.playStatus) { case 0: this.source.start() break case 1: this.setSource(this.audioBuffer) // 重新设置buffer this.source.start() break case 2: return false } this.source.playStatus = 2 } } /* 实例上监听 */ addEventListener(eventName, callback) { if (!this.handle[eventName]) { this.handle[eventName] = [] } this.handle[eventName].push(callback) } setSource(buffer) { this.source = null // 销毁掉旧的source this.source = this.context.createBufferSource() this.source.buffer = buffer this.source.loop = this.loop this.source.connect(this.context.destination) this.source.playStatus = 0 this.source.onended = () => { this.source.playStatus = 1 } } /* 创建source */ initSource(arrayBuffer) { const that = this that.context.decodeAudioData(arrayBuffer, function (buffer) { that.audioBuffer = buffer // 缓存起来 that.setSource(buffer) const event = that.handle['load'] if (event) { event.map(v => v.call(that)) } }, function (error) { const event = that.handle['error'] if (event) { event.map(v => v.call(that, error)) } }); } /* 使用xhr加载音乐文件 */ loadMusic() { const that = this const xhr = new XMLHttpRequest() xhr.open('GET', that.url, true) xhr.responseType = 'arraybuffer' xhr.send() xhr.addEventListener('load', function (e) { that.initSource(e.target.response) }) xhr.addEventListener('error', function (error) { const event = that.handle['error'] if (event) { event.map(v => v.call(that, error)) } }) }}export default Music
### 具体在VUE中使用
<template > <div @click="gotoMusic">div>template>
### 引入封装好的音乐播放
import AutoMusic from "@/music/autoMusic.js"
这个路径只是个列子,具体的还得根据你们实际的项目去改哦~~~
##### data中
data() { retrue { // 控制音乐播放 playMusic: false, music: null, }}
##### mounted中
mounted() { this.init()}
##### methods中
init() { this.music = new AutoMusic('/music/after.mp3', true) this.music.addEventListener('load', () => { this.music.play() this.playing = true })},gotoMusic() { this.playMusic = !this.playMusic; this.playMusic ? this.music.stop() : this.music.play()},
好啦,到这里已经可以使用背景音乐播放啦~~~~