`post-detail.js`
~~~javascript
onMusicTap:function(event){
var currentPostId = this.data.currentPostId;
var postData = postsData.postList[currentPostId];
var isPlayingMusic = this.data.isPlayingMusic;
if(isPlayingMusic){
wx.pauseBackgroundAudio();
this.setData({
isPlayingMusic:false
});
}else{
wx.playBackgroundAudio({
dataUrl:postData.music.url,
title: postData.music.title,
coverImgUrl: postData.music.coverImg
});
this.setData({
isPlayingMusic:true
});
}
},
~~~
`post-detail.wxml`
~~~html
<image catchtap="onMusicTap" class="audio" src="{{isPlayingMusic?'/images/music/music-stop.png':'/images/music/music-start.png'}}"></image>
~~~
### 音乐播放时切换头图
```html
<image class="head-image" src="{{isPlayingMusic?music.coverImg:headImgSrc}}"></image>
```
### 总控开关同步
onload方法当中
~~~javascript
var that = this;
wx.onBackgroundAudioPlay(function(){
that.setData({
isPlayingMusic:true
});
});
wx.onBackgroundAudioPause(function(){
that.setData({
isPlayingMusic: false
});
});
~~~
### 解决跳到其他页面中音乐播放状态问题
app.js中注册一个全局变量
~~~javascript
App({
globalData:{
g_isPlayingMusic:false,
}
})
~~~
`post-detail.js`的onload中增加全局音乐状态控制
~~~
// 获取全局变量
var app = getApp();
~~~
~~~
***if(app.globalData.g_isPlayingMusic){
this.setData({
isPlayingMusic:true
});
}
// 监听音乐播放总控
var that = this;
wx.onBackgroundAudioPlay(function(){
that.setData({
isPlayingMusic:true
});
***app.globalData.g_isPlayingMusic = true;
});
wx.onBackgroundAudioPause(function(){
that.setData({
isPlayingMusic: false
});
***app.globalData.g_isPlayingMusic = false;
});
~~~
### 解决跳转到其他页面中音乐播放内容错误的问题
~~~javascript
App({
globalData:{
g_isPlayingMusic:false,
g_currentMusicPostId:null
}
})
~~~
~~~javascript
** if (app.globalData.g_isPlayingMusic && app.globalData.g_currentMusicPostId==postId){
this.setData({
isPlayingMusic:true
});
}
// 监听音乐播放总控
var that = this;
wx.onBackgroundAudioPlay(function(){
that.setData({
isPlayingMusic:true
});
app.globalData.g_isPlayingMusic = true;
** app.g_currentMusicPostId = that.data.currentPostId;
});
wx.onBackgroundAudioPause(function(){
that.setData({
isPlayingMusic: false
});
app.globalData.g_isPlayingMusic = false;
** app.g_currentMusicPostId = null;
});
~~~
### 补充:banner跳转详情页
~~~html
<swiper-item>
<image catchtap="onSwiperItemTap" src='/images/wx.png' data-postId="3"></image>
</swiper-item>
<swiper-item>
<image catchtap="onSwiperItemTap" src='/images/vr.png' data-postId="4"></image>
</swiper-item>
<swiper-item>
<image catchtap="onSwiperItemTap" src='/images/iqiyi.png' data-postId="5"></image>
</swiper-item>
~~~
~~~js
onSwiperItemTap:function(event){
var postId = event.currentTarget.dataset.postid;
console.log(postId);
wx.navigateTo({
url: 'post-detail/post-detail?id=' + postId,
})
},
~~~