[TOC]
# 用组件写音乐播放器
## wxml
```
<image src="{{isPlay?play:pause}}" class="m-play" bind:tap="onMusic"></image>
```
## js
```
const audio = wx.getBackgroundAudioManager();
Component({
/**
* 组件的属性列表
*/
properties: {
image:String,
content:String,
url:String,
title:String
},
/**
* 组件的初始数据
*/
data: {
isPlay:false,
play:"images/play.png",
pause:"images/pause.png"
},
/**
* 组件的方法列表
*/
methods: {
onMusic(){
if(this.data.isPlay){
audio.pause();
this.setData({
isPlay:false
})
}else{
audio.title = this.properties.title;
audio.src=this.properties.url;
this.setData({
isPlay:true
})
}
},
_recoveryMusic(){
if(audio.src==this.properties.url){
this.setData({
isPlay:true
})
}
if(audio.paused){
this.setData({
isPlay:false
})
}
},
//监听
_monitorMusic(){
//监听音乐播放
audio.onPlay(() => {
this.setData({
isPlay: true
})
})
//监听音乐停止
audio.onPause(() => {
this.setData({
isPlay: false
})
})
audio.onStop(() => {
this.setData({
isPlay: false
})
})
audio.onEnded(() => {
this.setData({
isPlay: false
})
})
}
},
attached(){
this._recoveryMusic();
this._monitorMusic();
}
})
```