近期为一家企业开发小程序,用户提出了在小程序中增加直播功能。所幸小程序本身就提供了直播组件。具体开发文档可见官方说明。
小程序直播是微信官方提供的商家经营工具。通过调用该组件,商家可以在小程序中实现直播互动与商品销售闭环。其开发部分主要参考官方文档,使用更多是在微信小程序后台的直播控制台中进行操作,具体参考官方的操作手册。
一、接入小程序组件
在小程序某个中间页面的json文件中加入组件引用:
"plugins": {"live-player-plugin": {"version": "1.3.2", // 注意填写该直播组件最新版本号,微信开发者工具调试时可获取最新版本号(复制时请去掉注释)"provider": "wx2b03c6e691cd7370" // 必须填该直播组件appid,该示例值即为直播组件appid(复制时请去掉注释)}
}
你的plugins可能不止一个,因此,主要是在json文档的plugins部分加入"live-player-plugin",代码中的注释部分需要删除。其中的版本部分需要根据直播组件版本更新记录中查询(如下图黄色部分)。至此就在小程序中引入了直播组件。

二、直播间列表
微信小程序直播间开发api主要参考下面的内容进行开发。
官方的文档地址为:获取直播间列表和回放 | 微信开放文档
该接口支持https调用和云调用,调用额度:100000次/一天。
因为我们开发的小程序主要是云开发方式,且为了减少鉴权的要求,因而使用云调用方式。
设计云函数:getLiveRooms:
exports.main = async (event, context) => {let start=event.start;let limit=event.limit;let result=''try {result= await cloud.openapi.liveBroadcast.getLiveInfo({start: start,limit: limit})} catch (error) {result=error}return result}
在小程序页面端调用该云函数:
async LoadRooms() {var that = this;wx.cloud.callFunction({name: 'getLiveRooms',data: {start: this.data.pageSize * this.data.pageIndex,limit: this.data.pageSize},success(res) {let result=res.result;console.log(result)if (result.errCode == 0) {that.setData({roomList: that.data.roomList.concat(result.roomInfo)});} else {if (that.data.pageIndex == 0) {that.setData({isEmpty: true});} else {that.setData({isNoData: true});}}}});},
wxml页面展示直播间列表:
<view wx:else="{{isEmpty}}"><view wx:for="{{roomList}}" wx:key="index"><navigator url="plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id={{item.roomid}}" class="room"><view style="font-weight: 800;opacity: 0.8;display: flex;justify-content: space-between;align-items: center;">{{item.name}}<subscribe room-id="{{item.roomid}}" width="80" height="20" font-size="12" color="#eee" background-color="#f88616" bindsubscribe="onSubscribe"></subscribe></view><image class="room_img" src="{{item.coverImg}}" mode="aspectFill"></image><view class="romm_desc"><text>主播:{{item.anchorName}}</text><text>{{tools.formatTime(item.startTime*1000)}}</text></view></navigator></view>
</view>
三、直播订阅组件使用
在wxml页面直接加入订阅组件:
<subscribe room-id="{{item.roomid}}" width="80" height="20"font-size="12" color="#eee" background-color="#f88616" bindsubscribe="onSubscribe">
</subscribe>
组件的宽度、高度、背景颜色、文字颜色等都可以自定义,只要传入每个房间的roomid即可。组件监听的时间为:onSubscribe,可以在其中进行其他操作。
四、一点说明
官方文档中可能由于更新不及时,或者多个文档会存在冲突,因此对如roomid,coverImg等等返回值对象的字段写法要进行调整。


















