vod视频播放

This commit is contained in:
cao123
2026-09-03 16:14:47 +08:00
parent 1033136997
commit de47ffc773
17 changed files with 355 additions and 692 deletions
+3 -2
View File
@@ -6,9 +6,10 @@
"disableScroll": true,
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar",
"my-video":"/components/my-video/my-video",
"my-video": "/components/my-video/my-video",
"van-tab": "@vant/weapp/tab/index",
"van-tabs": "@vant/weapp/tabs/index",
"my-quiz":"/components/my-quiz/my-quiz"
"my-quiz":"/components/my-quiz/my-quiz",
"my-player": "plugin://myPlugin/player"
}
}
+9
View File
@@ -142,3 +142,12 @@ rich-content img {
height: 80rpx;
}
}
.cover {
position: absolute;
bottom: 0;
z-index: 998;
height: 20%;
width: 70%;
left: 10%;
background-color: rgba(255, 255, 255, 0.007);
}
+318 -287
View File
@@ -3,8 +3,9 @@
import UrlParamsHandler from "../../../utils/store";
import { htmlToWxNodes } from "../../../utils/html-to-wx-nodes";
import { request } from "../../../utils/request";
import { appId } from "../../../env";
import { AES_IV, AES_KEY, appId } from "../../../env";
import { receiveRedPacket } from "../../../utils/util";
import { aesEncrypt } from "../../../utils/crypto";
const isMobileEnvironment = (): boolean => {
const platform = wx.getSystemInfoSync().platform?.toLowerCase() || '';
@@ -12,6 +13,15 @@ const isMobileEnvironment = (): boolean => {
};
Page({
_wasPlayingBeforeInterrupt: false,
_pauseVideoHandler: null as any,
_resumeVideoHandler: null as any,
_appHideHandler: null as any,
_appShowHandler: null as any,
_networkStatusChangeHandler: null as any,
_videoContext: null as any,
/**
* 页面的初始数据
*/
@@ -20,10 +30,15 @@ Page({
nodes: [] as any[],
eveId: null,
store: {},
fileid: "5001834818839455549",
active: 0,
canSubmit: false,
safeBottom: 0,
safeBottom: 24,
resumeTime: 0,
playing: false,
currentTime: 0,
sendDurationTimer: 0,
isAppHidden: false,
},
/**
@@ -31,240 +46,305 @@ Page({
*/
async onLoad(options: any) {
const app = getApp<IAppOption>();
wx.hideShareMenu({
menus: ["shareAppMessage"], // 单独禁用好友分享
});
wx.hideShareMenu({ menus: ["shareAppMessage"] });
new UrlParamsHandler(options);
app.globalData.store = options;
let safeBottom = 0;
//@ts-ignore
if (wx.getWindowInfo) {
let safeBottom = 24;
try {
//@ts-ignore
const systemInfo = wx.getWindowInfo();
safeBottom =
Math.abs(systemInfo.windowHeight - systemInfo.safeArea.bottom) + 10;
const systemInfo = wx.getWindowInfo ? wx.getWindowInfo() : wx.getSystemInfoSync();
safeBottom = Math.abs(systemInfo.windowHeight - systemInfo.safeArea.bottom) + 10;
if (safeBottom === 0) safeBottom = 24;
} else {
const systemInfo = wx.getSystemInfoSync();
safeBottom = systemInfo.safeArea
? Math.abs(systemInfo.windowHeight - systemInfo.safeArea.bottom) + 10
: 24;
}
} catch (e) { }
this.setData({
safeBottom: safeBottom,
safeBottom,
store: options,
resumeTime: this.getResumeTime(),
});
this.initSystemListeners();
if (!isMobileEnvironment()) {
this.handleEnterError(
"当前环境不支持观看,请使用手机观看。",
"环境不支持",
);
this.handleEnterError("当前环境不支持观看,请使用手机观看。", "环境不支持");
return;
}
// 开启防截屏(仅限当前页面生命周期内)
//@ts-ignore
wx.setVisualEffectOnCapture({
visualEffect: 'hidden',
});
const bool = await app.login("video");
if (!bool) return;
//@ts-ignore 开启防截屏
if (wx.setVisualEffectOnCapture) wx.setVisualEffectOnCapture({ visualEffect: 'hidden' });
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady() { },
handleEnterError(message: string, title = "无法进入") {
wx.showModal({
title: title,
content: message,
showCancel: false,
confirmText: "确定",
});
},
handleBack() {
wx.switchTab({
url: "/pages/tab-bar/education/index",
});
},
/**
* 生命周期函数--监听页面显示
*/
onShow() {
this.search();
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide() {
// 离开视频页时恢复截屏能力,避免影响其他页面
//@ts-ignore
wx.setVisualEffectOnCapture({
visualEffect: 'none',
});
if (wx.setVisualEffectOnCapture) wx.setVisualEffectOnCapture({ visualEffect: 'none' });
if (this.data.currentTime > 0) {
wx.setStorageSync("interruptedTime", this.data.currentTime);
}
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload() {
// 卸载时恢复截屏能力
//@ts-ignore
wx.setVisualEffectOnCapture({
visualEffect: 'none',
});
if (wx.setVisualEffectOnCapture) wx.setVisualEffectOnCapture({ visualEffect: 'none' });
if (this.data.currentTime > 0) {
wx.setStorageSync("interruptedTime", this.data.currentTime);
wx.setStorageSync("currentTime", this.data.currentTime);
}
try {
this.pauseVideoBeforeNavigate();
} catch (err) { }
// 卸载时清理所有系统级监听与定时器
if (this._pauseVideoHandler) wx.offAudioInterruptionBegin(this._pauseVideoHandler);
if (this._resumeVideoHandler) wx.offAudioInterruptionEnd(this._resumeVideoHandler);
if (this._appHideHandler) wx.offAppHide(this._appHideHandler);
if (this._appShowHandler) wx.offAppShow(this._appShowHandler);
if (this._networkStatusChangeHandler) wx.offNetworkStatusChange(this._networkStatusChangeHandler);
this.clearSendProgressTimer();
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh() { },
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom() { },
/**
* 用户点击右上角分享
*/
onShareAppMessage() { },
onChange(event: any) {
this.setData({
active: event.detail.index,
this.setData({ active: event.detail.index });
},
initSystemListeners() {
this._networkStatusChangeHandler = (res: any) => {
if (!res.isConnected) {
wx.showToast({ title: '网络连接断开', icon: 'none' });
this.pauseVideoBeforeNavigate();
} else if (res.networkType !== 'wifi') {
wx.showToast({ title: '当前为非Wi-Fi环境,请注意流量消耗', icon: 'none' });
}
};
wx.onNetworkStatusChange(this._networkStatusChangeHandler);
this._pauseVideoHandler = () => {
this._wasPlayingBeforeInterrupt = this.data.playing;
this.pauseVideoBeforeNavigate();
};
this._resumeVideoHandler = () => {
const wasPlaying = this._wasPlayingBeforeInterrupt;
this._wasPlayingBeforeInterrupt = false;
if (wasPlaying && !this.data.isAppHidden) {
this.resumeVideoAfterInterrupt();
}
};
this._appHideHandler = () => {
this.setData({ isAppHidden: true });
this.pauseVideoBeforeNavigate();
};
this._appShowHandler = () => {
this.setData({ isAppHidden: false });
};
wx.onAudioInterruptionBegin(this._pauseVideoHandler);
wx.onAudioInterruptionEnd(this._resumeVideoHandler);
wx.onAppHide(this._appHideHandler);
wx.onAppShow(this._appShowHandler);
},
getVideoContext() {
if (!this._videoContext) {
this._videoContext = wx.createVideoContext("myPlayerId", this);
}
return this._videoContext;
},
pauseVideoBeforeNavigate() {
this.getVideoContext().pause();
},
resumeVideoAfterInterrupt() {
this.getVideoContext().play();
},
syncResumeTime() {
if (this.data.resumeTime > 0) {
this.getVideoContext().seek(this.data.resumeTime);
}
},
onPlayerPlay() {
this.setData({ playing: true, resumeTime: 0 });
wx.removeStorageSync("interruptedTime");
this.startSendProgress();
},
onPlayerPause() {
this.setData({ playing: false });
this.clearSendProgressTimer();
// 用户主动点击暂停时,存入进度
if (this.data.currentTime > 0) {
wx.setStorageSync("interruptedTime", this.data.currentTime);
}
},
onPlayerEnded() {
this.setData({ playing: false, resumeTime: 0 });
wx.setStorageSync("ended", true);
this.clearSendProgressTimer();
wx.removeStorageSync("interruptedTime");
wx.removeStorageSync("currentTime");
},
onPlayerError(e: any) {
const detail = (e && e.detail) || e || {};
wx.showModal({
title: "播放出错",
content: String(detail.errMsg || detail.message || JSON.stringify(detail)),
showCancel: false,
});
},
// 监听答题变化
// 接收原生组件的时间更新
onPlayerTimeUpdate(e: any) {
// 兼容 VOD 插件可能多包一层 detail 的情况
let time = e.detail?.currentTime ?? e.detail?.detail?.currentTime;
if (typeof time === 'number' && time > 0) {
const currentTime = Math.floor(time);
this.data.currentTime = currentTime; // 纯内存更新,不触发无用渲染
// 每 5 秒落盘一次 currentTime 作为终极兜底,不要太频繁避免卡顿
if (currentTime % 5 === 0) {
wx.setStorageSync("currentTime", currentTime);
}
}
},
getResumeTime(): number {
if (wx.getStorageSync("ended")) return 0;
const interrupted = Number(wx.getStorageSync("interruptedTime") || 0);
const current = Number(wx.getStorageSync("currentTime") || 0);
return Math.max(interrupted, current);
},
startSendProgress() {
this.clearSendProgressTimer();
this.sendProgress();
const timer = setInterval(() => {
this.sendProgress();
}, 15000) as unknown as number;
this.setData({ sendDurationTimer: timer });
},
clearSendProgressTimer() {
if (this.data.sendDurationTimer) {
clearInterval(this.data.sendDurationTimer);
this.setData({ sendDurationTimer: 0 });
}
},
async sendProgress() {
if (!this.data.playing) return;
try {
const openId = wx.getStorageSync("openId");
const code = wx.getStorageSync("code");
const state = wx.getStorageSync("state");
const seeId = wx.getStorageSync("seeId");
// 视频时长兜底补偿
const duration = this.data.currentTime + 1;
const url = code ? `/app/video-watch/inspect` : `/app/watch/inspect`;
const params = code ? { openId, code, duration } : { openId, state, seeId, duration };
await request({
options: {
url,
data: aesEncrypt(JSON.stringify(params), AES_KEY, AES_IV),
},
isLoading: false,
});
} catch (err) {
console.error("上报观看进度失败:", err);
}
},
onAnswerChange() {
this.updateProgress();
},
async search() {
const app = getApp<IAppOption>();
if (!(await app.checkLoginState())) return;
const code = wx.getStorageSync("code");
const params = {
openId: wx.getStorageSync("openId"),
...app.globalData.store,
};
if (code) {
const data = await request({
options: {
url: `/app/video-watch/simple-details`,
method: "GET",
data: params,
},
});
const params = { openId: wx.getStorageSync("openId"), ...app.globalData.store };
if (!data.watch.url) {
wx.reLaunch({
url: `/pages/live/registration/registration?content=${data.watch.content}&state=${-1}`,
});
}
const nodes = htmlToWxNodes(data.watch.content);
this.setData({
dataList: data.watch,
eveId: data.watch.eveId,
nodes,
});
} else {
const data = await request({
options: {
url: `/app/watch/simple-details`,
data: params,
},
});
const url = code ? `/app/video-watch/details` : `/app/watch/details`;
const data = await request({
options: { url, method: code ? "GET" : "POST", data: params },
});
if (!data.data.url) {
wx.reLaunch({
url: `/pages/live/registration/registration?content=${data.data.content
}&state=${5}`,
});
}
const nodes = htmlToWxNodes(data.data.content);
this.setData({
dataList: data.data,
eveId: data.data.eveId,
nodes,
const targetData = code ? data.watch : data.data;
if (!targetData?.url) {
const stateParam = code ? -1 : 5;
wx.reLaunch({
url: `/pages/live/registration/registration?content=${targetData?.content || ''}&state=${stateParam}`,
});
return;
}
this.selectComponent("#tabs").resize();
this.setData({
dataList: targetData,
eveId: targetData.eveId,
nodes: htmlToWxNodes(targetData.content),
});
this.syncResumeTime();
this.selectComponent("#tabs")?.resize();
},
// 更新答题进度
updateProgress() {
const quizComponent = this.selectComponent("#quizComponent");
if (quizComponent) {
const canSubmit = quizComponent.isAllAnswered();
this.setData({
canSubmit: canSubmit,
});
this.setData({ canSubmit: quizComponent.isAllAnswered() });
}
},
handleSubmit(this) {
const ended = wx.getStorageSync("ended") || false;
if (!ended) {
wx.showModal({
title: "请先观看视频,再答题",
showCancel: false,
confirmText: "确定",
confirmColor: "#FF0000",
});
return;
handleSubmit() {
if (!wx.getStorageSync("ended")) {
return wx.showModal({ title: "请先观看完整视频,再答题", showCancel: false, confirmColor: "#FF0000" });
}
//@ts-ignore
if (this.data.dataList?.userAnsNum >= this.data.dataList?.answerMax) {
wx.showToast({
title: "答题次数已用完",
icon: "none",
duration: 6000,
});
return;
return wx.showToast({ title: "答题次数已用完", icon: "none", duration: 3000 });
}
const quizComponent = this.selectComponent("#quizComponent");
if (!quizComponent) return wx.showToast({ title: "组件加载失败", icon: "none" });
if (!quizComponent) {
wx.showToast({
title: "组件加载失败",
icon: "none",
});
return;
}
const isAllAnswered = quizComponent.isAllAnswered();
if (!isAllAnswered) {
if (!quizComponent.isAllAnswered()) {
const progress = quizComponent.getProgress();
wx.showModal({
return wx.showModal({
title: "答题未完成",
content: `您已完成 ${progress.answered}/${progress.total} 题,请完成所有题目后再提交。`,
showCancel: false,
confirmText: "继续答题",
});
return;
}
const answers = quizComponent.getAllAnswers();
if (!answers || answers.length === 0) {
wx.showToast({
title: "请先完成答题",
icon: "none",
});
return;
}
if (!answers?.length) return wx.showToast({ title: "请先完成答题", icon: "none" });
wx.showModal({
title: "确认提交",
content: `您已完成 ${answers.length} 道题目,确定要提交答案吗?`,
success: (res) => {
if (res.confirm) {
this.submitAnswers(answers);
}
},
success: (res) => { if (res.confirm) this.submitAnswers(answers); },
});
},
@@ -276,145 +356,96 @@ Page({
eveId: this.data.eveId,
...this.data.store,
};
wx.showLoading({
title: "提交中...",
});
let res = null;
if (code) {
res = await request({
options: {
url: "/app/video-watch/interactive",
data: params,
wx.showLoading({ title: "提交中..." });
const url = code ? "/app/video-watch/interactive" : "/app/watch/interactive";
const res = await request({ options: { url, data: params } });
wx.hideLoading();
if (res.code !== 200) {
return wx.showToast({ title: res.msg || "提交失败", icon: "none", duration: 2000 });
}
const { pass, redPackage } = res.data || {};
if (pass) {
wx.showModal({
content: "🎉 回答正确,领取红包!",
showCancel: false,
confirmText: "立即领取",
confirmColor: "#FF0000",
success: async (res) => {
if (res.confirm) {
if (redPackage?.packageInfo) {
this.transferRedPacket(redPackage);
} else if (redPackage?.redId) {
await this.handleReceive(redPackage.redId);
}
}
},
});
} else {
res = await request({
options: {
url: "/app/watch/interactive",
data: params,
},
});
wx.showToast({ title: "回答错误,与红包擦肩而过", icon: "none", duration: 3000 });
}
if (res.code !== 200) {
wx.showToast({
title: res.msg || "提交失败",
icon: "none",
duration: 2000,
});
return;
}
const { pass } = res.data || {};
if (pass) {
wx.showToast({
title: "提交成功",
icon: "success",
duration: 2000,
});
}
// if (pass) {
// wx.showModal({
// content: "🎉 领取红包!",
// showCancel: false,
// confirmText: "立即领取",
// confirmColor: "#FF0000",
// success: async (res) => {
// if (res.confirm) {
// if (redPackage?.packageInfo) {
// try {
// wx.showLoading({ title: "领取中", mask: true });
// if (wx.canIUse?.("requestMerchantTransfer")) {
// await new Promise<void>((resolve, reject) => {
// // @ts-ignore
// wx.requestMerchantTransfer({
// mchId: redPackage.mchId,
// appId,
// package: redPackage.packageInfo,
// success: () => {
// wx.showToast({ title: "领取成功", icon: "success" });
// resolve();
// },
// fail: (err: any) => {
// console.error("拉起转账失败:", err);
// wx.showToast({ title: "领取失败", icon: "none" });
// reject(new Error(err?.errMsg || "领取失败"));
// },
// });
// });
// } else {
// wx.showModal({
// content: "你的微信版本过低,请更新至最新版本。",
// showCancel: false,
// });
// throw new Error("微信版本过低");
// }
// } catch (err: any) {
// wx.hideLoading();
// const msg = err?.data?.msg || err?.errMsg || err?.message || "领取失败";
// wx.showToast({ title: msg, icon: "none" });
// }
// } else {
// await this.handleReceive(redPackage.redId);
// }
// }
// },
// });
// } else {
// wx.showToast({
// title: "回答错误,您与红包擦肩而过",
// icon: "none",
// duration: 6000,
// });
// }
},
async handleReceive(id: any) {
const { code } = this.data.store as Record<string, any>;
const params = {
appId,
code,
openId: wx.getStorageSync("openId"),
redId: id,
async transferRedPacket(redPackage: any) {
wx.showLoading({ title: "领取中", mask: true });
if (!wx.canIUse?.("requestMerchantTransfer")) {
wx.hideLoading();
return wx.showModal({ content: "你的微信版本过低,请更新至最新版本。", showCancel: false });
}
try {
await new Promise<void>((resolve, reject) => {
// @ts-ignore
wx.requestMerchantTransfer({
mchId: redPackage.mchId,
appId,
package: redPackage.packageInfo,
success: () => {
wx.hideLoading();
wx.showToast({ title: "领取成功", icon: "success" });
resolve();
},
fail: (err: any) => reject(new Error(err?.errMsg || "领取失败")),
});
});
} catch (err: any) {
wx.hideLoading();
wx.showToast({ title: err?.message || "领取失败", icon: "none" });
}
},
async handleReceive(id: any) {
const { code } = this.data.store as Record<string, any>;
try {
wx.showLoading({ title: "领取中" });
await receiveRedPacket(
params,
{ appId, code, openId: wx.getStorageSync("openId"), redId: id },
'/app/general/receive-red',
appId
);
wx.hideLoading();
} catch (err) {
wx.hideLoading();
console.error('领取红包失败:', err);
}
},
// 跳转前暂停视频播放
pauseVideoBeforeNavigate() {
const video = this.selectComponent("#myVideo") as any;
if (video && video.pauseVideo) {
video.pauseVideo();
}
handleEnterError(message: string, title = "无法进入") {
wx.showModal({ title, content: message, showCancel: false });
},
handleBack() {
wx.switchTab({ url: "/pages/tab-bar/course/course" });
},
handleCustomReport() {
this.pauseVideoBeforeNavigate();
const { code, state, seeId } = this.data.store as Record<string, any>;
const params: Record<string, string> = {};
if (code) params.code = code;
if (state) params.state = state;
if (seeId) params.seeId = seeId;
wx.navigateTo({
url: `/pages/live/report/report`,
});
wx.navigateTo({ url: `/pages/live/report/report` });
},
handleViewHitory() {
this.pauseVideoBeforeNavigate();
const { code, state, seeId } = this.data.store as Record<string, any>;
const params: Record<string, string> = {};
if (code) params.code = code;
if (state) params.state = state;
if (seeId) params.seeId = seeId;
wx.navigateTo({
url: `/pages/live/red-history/red-history`,
});
wx.navigateTo({ url: `/pages/live/red-history/red-history` });
}
});
});
+19 -4
View File
@@ -9,8 +9,23 @@
<view style="display: flex; align-items: center; padding: 0 20rpx; height: 70rpx; background: #FFF7E6;">
<view style="font-size: 22rpx; color: #999;">本视频仅用于科普,无任何恶意引导行为</view>
</view>
<my-video id="myVideo" src="{{dataList.url}}" backgroundUrl="{{dataList.background}}"></my-video>
<!-- VOD 云点播短视频插件方案:续播 seek / 进度缓存上报 / 电话中断恢复 / 全屏状态同步 -->
<my-player
width="100%"
height="210px"
appid="1304584727"
fileid="{{fileid}}"
enable-progress-gesture="{{false}}"
playerid="myPlayerId"
bindplay="onPlayerPlay"
bindpause="onPlayerPause"
bindended="onPlayerEnded"
binderror="onPlayerError"
bindtimeupdate="onPlayerTimeUpdate"
show-fullscreen-btn
>
<cover-view class="cover"></cover-view>
</my-player>
<block wx:if="{{dataList.tipUrl}}">
<image alt="提示" mode="widthFix" src="{{dataList.tipUrl}}" style="width: 100%" />
</block>
@@ -32,8 +47,8 @@
</view>
</scroll-view>
</van-tab>
<!-- <view class="history" bind:tap="handleViewHitory">
<view class="history" bind:tap="handleViewHitory">
<image class="icon" src="./assets/1.png" />
</view> -->
</view>
</van-tabs>
</scroll-view>