音乐播放,为什么需要点击两遍,才开始播放?
用wx.createInnerAudioContext()接口封装了一个组件叫audio,但是每次点击两遍播放之后,才能开始播放,是什么原因呢?
components/audio/audio.js
// components/audio/audio.js
Component({
properties: {
//音频地址
src: {
type: String,
value: '',
},
//图书封面图片
poster: {
type: String,
value: ''
}
},
data: {
audioContext: null, //
src: "",
currentTime: 0,
duration: 0,
flag: "play" //play 显示播放按钮;load 显示加载按钮;pause 显示暂停按钮
},
lifetimes: {
attached() {
this.data.audioContext = wx.createInnerAudioContext()
this.data.audioContext.src = this.data.src;
this.data.audioContext.loop=false;
this.data.src = this.properties.src;
this.data.poster = this.properties.poster;
},
detached: function () {
this.data.audioContext.destroy()
}
},
methods: {
//音频播放
play() {
this.data.audioContext.play()
this.setData({
flag: "load"
})
//开始播放瞬间
this.data.audioContext.onCanplay(() => {
this.setData({
flag: "pause"
})
this.timeUpdate()
})
},
//暂停播放
pause() {
this.data.audioContext.pause()
this.setData({
flag: "play"
})
},
timeUpdate() {
//播放过程中
this.data.audioContext.onTimeUpdate((res) => {
let currentTime = this.data.audioContext.currentTime;
let duration = this.data.audioContext.duration;
this.setData({
currentTime,
duration
})
})
},
//滑块滚动
handleSlider(e) {
var value = e.detail.value;
console.log(e, '1111')
this.data.audio.seek(value)
},
//点击大图
posterClick() {
wx.previewImage({
urls: [this.properties.poster],
})
}
},
})
components/audio/audio.json
{
"component": true,
"usingComponents": {
"mp-icon": "weui-miniprogram/icon/icon"
}
}
comsponents/audio/audio.wxml
<view class="top">
<image class="poster" mode="aspectFill" src="{{poster}}" class="book" bindtap="posterClick"></image>
<view class="bof">
<view class="time">{{currentTime}}</view>
<slider block-size="12" min="0" max="{{duration}}" activeColor="#07ab74" class="slider" value="{{currentTime}}" bindchange="handleSlider">
</slider>
<view class="time">{{duration}}</view>
</view>
<view class="a">
<mp-icon wx:if="{{flag=='play'}}" icon="play2" color="#07ab74" size="60" type="field" bindtap="play" />
<image wx:elif="{{flag=='load'}}" class="load" src="./images/load.png" mode="aspectFit"></image>
<mp-icon wx:else icon="pause" color="#07ab74" size="60" type="field" bindtap="pause" />
</view>
<view>{{currentTime}}</view>
</view>