有奖:语音产品征文挑战赛火热进行中> HOT
本文主要为您介绍如何在小程序端播放 HLS 加密视频。


前置步骤

创建加密视频搭建 token 服务,详情请参见 HLS 视频加密播概述


小程序端播放指引

由于小程序端的 video 标签是原生支持 HLS 格式,所以以下步骤主要是计算和拼接一个可以正常被 video 标签播放的地址。步骤如下:
1. 新建小程序工程代码,在 pages/index/index.wxml 里加 video 标签。
<video src="{{src}}"></video>
2. 在 pages/index/index.js 里填入以下代码示例。
Page({
data: {
// 将要播放的转码后的 m3u8 视频链接
m3u8Url: 'https://example-1250000000.cos.ap-beijing.myqcloud.com/hls/video.m3u8',
src: '',
},
onReady: async function () {
wx.request({
method: 'POST',
// 替换成自己实现的 hls token server
// token server 参考文档:https://cloud.tencent.com/document/product/460/104024#5ea2a185-f626-4f4c-9011-cc7684c39baf
// token server 代码示例:https://github.com/tencentyun/cos-demo/tree/main/server/hls-decrypt-token/
url: 'https://example.com/samples/hls/token',
data: JSON.stringify({
src: this.data.m3u8Url,
protectContentKey: 0,
}),
header: {
'Content-Type': 'application/json',
},
dataType: 'json',
success: (res) => {
const {token, authorization} = res.data;
// 拼接可被正常 HLS 标准加密方式播放的视频链接,加上签名、token等参数
const url = `${this.data.m3u8Url}?ci-process=pm3u8&expires=43200&tokenType=JwtToken&token=${encodeURIComponent(token)}&${authorization}`;
this.setData({ src: url });
},
fail(res) {
console.log(res);
},
});
}
})
3. 在小程序开发工具上打开项目编译,即可正常播放 HLS 加密视频。


相关文档