安装createjs-npm
npm install createjs-npm -S

<template>
	<view @click="music_click">{{isplay?'暂停':'播放'}}</view>
	
</template>
<script>
//或者在html引入<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
import createjs from 'createjs-npm';  
export default {
	data(){
		return {
			isplay: false,
			ispause: true,
			bg_music_state: 'pause',
			instance: null, //背景音乐播放
			bg_music: 'xxxx',  //背景音乐路径
		}
	},
	onLoad(options) {
		this.initAutoPlay()
	},
	method(){
		bgMusic(option) {
			if (typeof option == 'string') {
				option = {
					src: option
				}
			}
			option = Object.assign({
				src: '',
				loop: 999,
				elementId: 'bgmusic'
			}, option)
			createjs.Sound.alternateExtensions = ['mp3']
			createjs.Sound.on(
				'fileload',
				(event) => {
					this.handleLoad(option)
				},
				window
			)
			createjs.Sound.registerSound(option.src, option.elementId)
			//默认播放
			this.bg_music_state = 'play'
			this.isplay = true
			this.ispause = false
		},
		handleLoad(option) {
			this.instance = createjs.Sound.play(option.elementId)
			this.instance.loop = option.loop
		},
		//初始化播放
		initAutoPlay() {
			this.bgMusic(this.bg_music)  //播放路径
		},
		//操作
		music_click() {
			if (this.bg_music_state === 'play') {
				//暂停
				this.instance.paused = true  //暂停播放
				//instance.volume = 1   //播放音量
				this.bg_music_state = 'pause'
				this.isplay = false
				this.ispause = true
			} else {
				//播放
				this.instance.paused = false  //继续播放
				this.bg_music_state = 'play'
				//instance.volume = 1   //播放音量
				this.isplay = true
				this.ispause = false
			}
		},
	}
}
</script>

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部