前言
在微信小程序项目中遇到的需求是这样的,列表点击可播放音频内容且只能播放一个音频即:
- 点击列表1播放当前音频内容
- 点击列表2,播放列表2音频内容,同时停止列表1音频播放
- ….
微信小程序~wx.createInnerAudioContext
wx.createInnerAudioContext~功能描述:
创建内部 audio 上下文 InnerAudioContext 对象
1 2 3 4 5 6 7 8 9 10 11 12
| const innerAudioContext = wx.createInnerAudioContext({ useWebAudioImplement: false }) innerAudioContext.src = 'http://ws.stream.qqmusic.qq.com/M500001VfvsJ21xFqb.mp3?guid=ffffffff82def4af4b12b3cd9337d5e7&uin=346897220&vkey=6292F51E1E384E061FF02C31F716658E5C81F5594D561F2E88B854E81CAAB7806D5E4F103E55D33C16F3FAC506D1AB172DE8600B37E43FAD&fromtag=46'
innerAudioContext.play()
innerAudioContext.pause()
innerAudioContext.stop()
innerAudioContext.destroy()
|
注意事项
InnerAudioContext 音频资源不会自动释放,
因此如果不再需要使用音频请及时调用InnerAudioContext.destroy() 释放资源,避免内存泄漏。
以上是微信小程序官方文档的基本介绍
实现
- 点击音频列表中某项拿到autioOption、audioUrl、index、id这些内容
- 在播放音频事件click_audio中接收这类值,同时获取循环数据列表
- 判断active是否进行播放
- 循环数据列表内容,根据id进行修改音频状态
- this.setData进行数据同步返回并渲染
- 离开当前页时在onUnload生命周期中释放音频资源
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| let innerAudioContext = null; Page({ data: { list:[] }, onLoad(){ innerAudioContext = wx.createInnerAudioContext(); innerAudioContext.onPlay((e)=>{ }) innerAudioContext.onStop((e)=>{ }) innerAudioContext.onPause(()=>{ }) }, click_audio:function(){ let active = e.currentTarget.dataset.active; let index = e.currentTarget.dataset.index; let sound = e.currentTarget.dataset.sound; let id = e.currentTarget.dataset.id; let list = this.data.list; if(active){ this.setData({ ['list['+ index + '].activeAudio']:false, }) innerAudioContext.pause(); }else{ let newList = []; list.forEach((item) => { if(id == item.id){ item.autioOption=true; } else{ item.autioOption=false; } newList.push(item); }); this.setData({ list:newList }); innerAudioContext.src = sound; innerAudioContext.play(); } }, onUnload(){ let newList = []; let list = this.data.list; list.forEach((item) => { item.autioOption=false; newList.push(item); }); this.setData({ list:newList }); innerAudioContext.destroy(); } })
|
- active/autioOption 当前是否播放音频状态
- index 选中的音频内容下标
- sound 选中的音频播放内容
- id 音频的唯一标识
1 2 3 4 5 6 7 8 9 10
| <view wx:for="{{list}}" wx:key="unique" bindtap="click_audio" data-active = "{{item.autioOption}}" data-sound="{{item.audioUrl}}" data-index="{{index}}" data-id="{{item.id}}"> </view>
|
点击效果,可以判断activeAudio进行动态class判定即可。
列表点赞~思路
以上的实现内容很像类似于列表点赞或是列表点击某个内容同步后台数据等等
小程序的写法需要通过this.setData进行数据绑定
通过Vue的方式去写以上的方法基本代码思路基本不变,
- 点击列表内容获取当前点赞量,id
- 在点击列表事件中接收点赞量,id,
- 通过后端提供的接口返回相关内容,点赞量+1
- 同步当前数据并渲染列表点赞量内容,(注意不需要页面刷新或是重新请求全部列表数据接口)
取消点赞也基本跟上述一样的方式,根据业务流程的不同做出相应改变
结尾
以上就是关于微信小程序音频播放wx.createInnerAudioContext的详细使用的全部内容了
不热衷于视觉设计的开发者不是一个好作家。 —— 贤心
这是在layui官网中看到的一句话,在此分享。