| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176 |
- <template>
- <view class="video-player-container">
- <!-- 直播状态显示 -->
- <view class="videolist" v-if="liveItem.status == 2" :class="isFullscreen ? 'screen' : ''">
- <view class="video" :class="{'video_row': liveItem.showType == 1,'fullscreen-mode': isFullscreen}">
- <!-- 直播 -->
- <live-player v-if="liveItem.livingUrl && liveItem.liveType == 1" :id="'myLivePlayer_' + liveId"
- :src="liveItem.livingUrl" autoplay mode="live" object-fit="cover" :muted="false"
- orientation="vertical" :enable-play-gesture="false" min-cache="1" max-cache="3"
- @statechange="onLiveStateChange" @error="onLiveError" class="item"></live-player>
- <!-- 录播 -->
- <video v-if="liveItem.videoUrl && liveItem.liveType == 2" :id="`myVideo_${liveId}`" :autoplay="true"
- class="item" :src="liveItem.videoUrl" :controls="false"
- :object-fit="liveItem.showType==2||isFullscreen?'contain':'fill'" :custom-cache="false"
- :enable-progress-gesture="false" vslide-gesture-in-fullscreen="false" :show-center-play-btn="false"
- :http-cache="false" loop @error="videoError" @timeupdate="onVideoTimeUpdate"
- @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
- @waiting="onVideoWaiting" :enable-play-gesture="false" :play-strategy="1"
- @dblclick="preventDoubleClick" preload="auto" :enable-stash-buffer="false" :stash-initial-size="0"
- :stash-max-size="0" :stash-time="0" type="application/x-mpegURL"></video>
- <view v-if="liveItem.videoUrl && liveItem.liveType == 2" class="time"
- :class="isFullscreen ? 'look-time' : 'time'">{{ diffTotalTime }}</view>
- <view class="custom-controls" @click.stop="toggleFullscreen">
- <image src="/static/images/full_screen.png" class="control-icon" />
- </view>
- <!-- 全屏返回按钮 - 只在全屏状态下显示 -->
- <view v-if="isFullscreen" class="fullscreen-exit-btn" @click="exitFullscreen">
- <image src="/static/images/half_screen.png" class="exit-fullscreen-icon" />
- <text class="exit-text">退出全屏</text>
- </view>
- </view>
- </view>
- <!-- 直播结束状态 -->
- <view class="videolist" v-if="liveItem.status == 3">
- <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
- <view class="end">直播已结束</view>
- </view>
- </view>
- <!-- 直播回放状态 -->
- <view class="videolist" v-if="liveItem.status == 4">
- <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
- <!-- 直播回放 -->
- <video v-if="liveItem.videoUrl && liveItem.liveType == 3" :id="`myVideo_${liveId}`" class="item"
- :src="liveItem.videoUrl" :autoplay="true" :controls="true" object-fit="cover" :custom-cache="false"
- :enable-progress-gesture="liveItem.isSpeedAllowed" vslide-gesture-in-fullscreen="true"
- :show-center-play-btn="true" :http-cache="false" loop @error="videoError"
- @timeupdate="onVideoTimeUpdate" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause"
- @play="onVideoPlay" :enable-play-gesture="true" preload="auto" @waiting="onVideoWaiting"
- type="application/x-mpegURL"></video>
- <view v-if="liveItem.videoUrl && liveItem.liveType == 3" class="lable">直播回放</view>
- </view>
- </view>
- <view class="trailer-box" v-if="liveItem.status == 1">
- <video v-if="liveItem.previewUrl" :id="`myVideo_${liveId}`" class="trailer-video" :src="liveItem.previewUrl"
- :autoplay="true" :loop="false" object-fit="cover" :custom-cache="false" :enable-progress-gesture="false"
- vslide-gesture-in-fullscreen="false" :show-center-play-btn="false" :http-cache="false"
- @error="videoError" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
- :disable-progress="true" :enable-play-gesture="true" @waiting="onVideoWaiting" preload="auto"
- type="application/x-mpegURL" :controls="false"></video>
- <image v-if="liveItem.status == 1 && !liveItem.previewUrl" class="trailer-placeholder"
- src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/no_live.png">
- </image>
- <view class="countdown-container" v-if="liveItem.status == 1 && liveCountdown">
- <view class="live-name">{{ liveItem.liveName }}</view>
- <view class="countdown-display">
- <text class="countdown-label">距离开播还有</text>
- <view class="countdown-unit">
- {{ liveCountdown.hours || '00' }}
- </view>
- <view class="countdown-separator">:</view>
- <view class="countdown-unit">
- {{ liveCountdown.minutes || '00' }}
- </view>
- <view class="countdown-separator">:</view>
- <view class="countdown-unit">
- {{ liveCountdown.seconds || '00' }}
- </view>
- </view>
- </view>
- <view class="trailer-actions">
- <button open-type="share" class="button-reset share-button">
- <view class="action-button mr18" @click="handleAgreement">
- <text>分享给好友</text>
- </view>
- </button>
- <view class="action-button reserve-button" @click="handleAgreement">
- <image class="button-icon mr8" src="/static/images/trailer.png"></image>
- <text>预约直播</text>
- </view>
- </view>
- </view>
- <!-- 无直播状态 -->
- <view class="trailer-box" v-if="!liveItem">
- <image class="img" src="/static/images/no_live.png"></image>
- <view class="title">暂无直播</view>
- </view>
- </view>
- </template>
- <script>
- import {
- generateRandomString
- } from '@/utils/common.js';
- import dayjs from 'dayjs';
- import {
- internetTraffic,
- liveInternetTraffic
- } from '@/api/living.js';
- import {
- getUserInfo
- } from '@/api/user';
- export default {
- name: 'LiveVideoPlayer',
- props: {
- liveItem: {
- type: Object,
- default: () => ({})
- },
- liveId: {
- type: [String, Number],
- default: ''
- },
- userData: {
- type: Object,
- default: () => ({})
- },
- isAgreement: {
- type: Boolean,
- default: false
- }
- },
- data() {
- return {
- isFullscreen: false,
- isVideoRotated: false,
- showNonVideoElementsFlag: true,
- showCustomControls: true,
- videoContext: null,
- // 流量计算相关
- uuId: '',
- totalTraffic: 0,
- bitrate: 800,
- bitrateLive: 1600,
- // 定时器
- trafficTimer: null,
- liveStartTimer: null,
- trafficInterval: null,
- lookTimer: null,
- // 状态数据
- liveCountdown: {},
- diffTotalTime: '',
- videoCurrentTime: 0,
- videoProgressKey: '',
- startTime: 0,
- stayTime: 0,
- // 内部状态跟踪
- hasInitialized: false,
- lastLiveItemStatus: null
- };
- },
- watch: {
- // 深度监听 liveItem 的所有变化
- liveItem: {
- handler(newVal, oldVal) {
- if (newVal && newVal.status === 1 && newVal.startTime) {
- // 如果是预告状态且有开始时间,立即启动倒计时
- this.startLiveCountdown();
- }
- },
- deep: true,
- immediate: true // 立即执行一次
- },
- // 单独监听 status 变化作为备用
- 'liveItem.status': {
- handler(newStatus, oldStatus) {
- console.log('状态变化:', oldStatus, '->', newStatus);
- if (newStatus === 1 && this.liveItem.startTime) {
- this.startLiveCountdown();
- } else if (newStatus === 2) {
- this.startTimeTimer(this.liveItem);
- }
- },
- immediate: true
- }
- },
- async created() {
- // 最早的可执行时机
- if (this.liveItem && Object.keys(this.liveItem).length > 0) {
- await this.initializeComponent();
- }
- },
- // async mounted() {
- // await this.initializeComponent();
- // },
- computed: {
- shouldShowNonVideoElements() {
- return !this.isFullscreen && this.showNonVideoElementsFlag;
- },
- // 控制是否显示全屏按钮
- shouldShowFullscreenButton() {
- return this.liveItem.showType == 1 && !this.isFullscreen;
- },
- },
- beforeUnmount() {
- this.cleanup();
- // 强制退出全屏
- this.isFullscreen = false;
- this.showCustomControls = true;
- },
- methods: {
- // 退出全屏
- exitFullscreen() {
- console.log('执行退出全屏');
- this.isFullscreen = false;
- // 显示非videolist元素
- this.showNonVideoElements();
- // 强制页面重排
- this.$nextTick(() => {
- this.$forceUpdate();
- this.$emit('fullscreen-change', this.isFullscreen);
- });
- },
- // 恢复videolist盒子
- restoreVideoList() {
- this.isVideoRotated = false;
- this.isFullscreen = false;
- },
- // 切换全屏
- toggleFullscreen() {
- // console.log('自定义全屏按钮被点击');
- if (this.isFullscreen) {
- // 退出全屏
- this.exitFullscreen();
- } else {
- // 进入全屏
- this.enterFullscreen();
- }
- }, // 进入全屏
- enterFullscreen() {
- console.log('执行进入全屏');
- this.isFullscreen = true;
- // 设置横屏样式
- this.rotateVideoList();
- // 隐藏非videolist元素
- this.hideNonVideoElements();
- this.$emit('fullscreen-change', this.isFullscreen);
- // 强制页面重排
- this.$forceUpdate();
- },
- // 隐藏非videolist元素
- hideNonVideoElements() {
- this.showNonVideoElementsFlag = false;
- console.log('隐藏非视频元素');
- },
- // 显示非videolist元素
- showNonVideoElements() {
- this.showNonVideoElementsFlag = true;
- },
- // 防止默认全屏事件
- onFullscreenChange(e) {
- // 阻止默认全屏行为
- e.preventDefault();
- // 如果有video进入全屏,立即退出
- if (e.detail && e.detail.fullScreen) {
- const videoContext = uni.createVideoContext(`myVideo_${this.liveId}`, this);
- if (videoContext) {
- setTimeout(() => {
- videoContext.exitFullScreen();
- }, 100);
- }
- }
- },
- // 旋转videolist盒子
- rotateVideoList() {
- this.isVideoRotated = true;
- this.isFullscreen = true;
- console.log('视频容器旋转到横屏状态');
- },
- // 全屏状态变化监听
- onFullscreenChange(e) {
- console.log('全屏状态变化事件详情:', e);
- // 方法1:通过事件参数获取(小程序主要方式)
- let fullScreen = false;
- // 视频组件的全屏事件参数
- if (e.detail && typeof e.detail.fullScreen !== 'undefined') {
- fullScreen = e.detail.fullScreen;
- console.log('通过e.detail.fullScreen获取全屏状态:', fullScreen);
- }
- // 其他可能的参数名
- else if (e.detail && typeof e.detail.fullscreen !== 'undefined') {
- fullScreen = e.detail.fullscreen;
- console.log('通过e.detail.fullscreen获取全屏状态:', fullScreen);
- }
- // 方法2:检测横屏(备用)
- else {
- // 在小程序环境中,可以通过屏幕方向判断
- try {
- const systemInfo = uni.getSystemInfoSync();
- fullScreen = systemInfo.windowWidth > systemInfo.windowHeight;
- console.log('通过屏幕方向判断全屏状态:', fullScreen);
- } catch (err) {
- console.error('获取系统信息失败:', err);
- // 默认使用事件参数
- fullScreen = e.detail || false;
- }
- }
- this.isFullscreen = fullScreen;
- console.log('最终设置isFullscreen为:', this.isFullscreen);
- // 根据全屏状态显示/隐藏自定义控件
- this.showCustomControls = !this.isFullscreen;
- // 强制UI更新
- this.$forceUpdate();
- // 全屏时锁定横屏
- if (this.isFullscreen) {
- this.lockOrientation();
- } else {
- this.unlockOrientation();
- }
- },
- // 锁定屏幕方向为横屏
- lockOrientation() {
- // 设置屏幕方向为横屏
- try {
- // 尝试锁定横屏
- plus.screen.lockOrientation('landscape-primary');
- } catch (e) {
- console.log('锁定屏幕方向失败:', e);
- // 备用方案
- try {
- // 使用 Web API(如果支持)
- if (screen.orientation && screen.orientation.lock) {
- screen.orientation.lock('landscape');
- }
- } catch (err) {
- console.log('备用方案也失败了:', err);
- }
- }
- }, // 解锁屏幕方向
- unlockOrientation() {
- try {
- plus.screen.unlockOrientation();
- } catch (e) {
- console.log('解锁屏幕方向失败:', e);
- // 备用方案
- try {
- if (screen.orientation && screen.orientation.unlock) {
- screen.orientation.unlock();
- }
- } catch (err) {
- console.log('备用解锁方案也失败了:', err);
- }
- }
- },
- handleAgreement() {
- console.log('预约直播点击');
- this.$emit('agreementClick');
- }, // 播放视频
- playVideo() {
- if (!this.liveItem) {
- console.log('liveItem 为空,无法播放视频');
- return;
- }
- try {
- // 直播流使用live-player
- if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
- const livePlayerId = `myLivePlayer_${this.liveId}`;
- const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
- // console.log("直播")
- if (livePlayerContext) {
- livePlayerContext.play();
- }
- } else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (videoContext) {
- videoContext.play();
- }
- } else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem.status == 2) {
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- // console.log("录播")
- if (videoContext) {
- videoContext.play();
- }
- } // 回放视频使用video
- else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem.status == 4) {
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- // console.log("回放")
- if (videoContext) {
- videoContext.play();
- }
- }
- } catch (error) {
- console.error('播放视频失败:', error);
- }
- },
- pauseVideo() {
- if (!this.liveItem) return;
- try {
- // 直播流使用live-player
- if (this.liveItem.status == 1) {
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (videoContext) {
- videoContext.pause();
- }
- } else if (this.liveItem.status == 2) {
- if (this.liveItem.liveType === 1) {
- const livePlayerId = `myLivePlayer_${this.liveId}`;
- const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
- if (livePlayerContext) {
- livePlayerContext.pause();
- }
- } else if (this.liveItem.liveType === 2) {
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (videoContext) {
- videoContext.pause();
- }
- }
- }
- } catch (error) {
- console.error('暂停视频失败:', error);
- }
- },
- // 视频错误处理
- videoError(e, liveItem) {
- if (!liveItem || !this.liveId) return;
- // 初始化重试计数
- if (this.videoRetryCounts[liveItem.liveId] === undefined) {
- this.videoRetryCounts[liveItem.liveId] = 0;
- }
- // 限制重试次数
- if (this.videoRetryCounts[liveItem.liveId] >= 3) {
- console.error(`直播间 ${this.liveId} 视频加载失败,停止重试`);
- // 显示错误提示
- uni.showToast({
- title: '视频加载失败,请检查网络',
- icon: 'none',
- duration: 2000
- });
- return;
- }
- this.videoRetryCounts[this.liveId]++;
- // 延迟重试
- setTimeout(() => {
- if (this.liveId === this.liveId) {
- console.log(`第${this.videoRetryCounts[this.liveId]}次重试播放视频`);
- this.playVideo();
- }
- }, 2000);
- }, // 视频暂停
- onVideoPause(e) {
- if (this.liveItem.liveType === 2) {
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- setTimeout(() => {
- videoContext.play();
- }, 100);
- }
- // 暂停时保存进度
- this.saveVideoProgress();
- }, //直播、录播缓冲
- getLiveInternetTraffic() {
- if (!this.liveId) return;
- const currentTime = (this.stayTime / this.liveItem.duration) * 100;
- const param = {
- userId: this.userData.userId || '',
- liveId: this.liveId || '',
- uuId: dayjs().format('YYYYMMDD') + this.uuId,
- internetTraffic: this.totalTraffic
- };
- liveInternetTraffic(param);
- },
- startTimer() {
- this.startTime = Date.now();
- this.lookTimer = setInterval(() => {
- this.stayTime = Math.floor((Date.now() - this.startTime) / 1000);
- }, 1000);
- },
- // 计算流量
- // calculateTraffic(bitrate) {
- // const currentTime = Date.now();
- // const duration = (currentTime - this.startTime) / 1000; // 持续时间(秒)
- // // 流量 = 码率 × 时间
- // // 码率单位: bps, 时间单位: 秒, 流量单位: 比特
- // const trafficBits = bitrate * duration;
- // // 转换为字节
- // this.totalTraffic = trafficBits / 8;
- // this.getLiveInternetTraffic();
- // },
- // 计算流量
- calculateTraffic(bitrate) {
- const currentTime = Date.now();
- const duration = (currentTime - this.startTime) / 1000; // 持续时间(秒)
- // 流量 = 码率 × 时间
- // 码率单位: bps, 时间单位: 秒, 流量单位: 比特
- const trafficBits = bitrate * duration;
- // 转换为字节
- this.totalTraffic = trafficBits / 8;
- // 调用流量上报接口
- this.getLiveInternetTraffic();
- },
- //直播计算流量
- // startTrafficCalculation(bitrate) {
- // if (this.trafficTimer) {
- // clearInterval(this.trafficTimer);
- // this.trafficTimer = null;
- // }
- // this.startTime = Date.now();
- // var that = this;
- // this.trafficTimer = setInterval(() => {
- // that.calculateTraffic(bitrate);
- // }, 10000); // 每10秒计算一次
- // },
- startTrafficCalculation() {
- if (this.trafficTimer) {
- clearInterval(this.trafficTimer);
- this.trafficTimer = null;
- }
- this.startTime = Date.now();
- var that = this;
- // 计算码率
- let bitrate = this.calculateBitrate();
- this.trafficTimer = setInterval(() => {
- that.calculateTraffic(bitrate);
- }, 10000); // 每10秒计算一次
- }, // 计算码率
- calculateBitrate() {
- // 如果接口返回了视频文件大小和时长,使用这些数据计算码率
- if (this.liveItem.videoFileSize && this.liveItem.videoDuration) {
- // 码率 = 文件大小(字节) / 时长(秒) × 8 (转换为bps) × 5
- const calculatedBitrate = (this.liveItem.videoFileSize / this.liveItem.videoDuration) * 8 * 5;
- console.log(
- `使用接口数据计算码率: ${calculatedBitrate} bps (文件大小: ${this.liveItem.videoFileSize} 字节, 时长: ${this.liveItem.videoDuration} 秒)`
- );
- return calculatedBitrate;
- } else {
- // 如果任一字段为空,使用默认码率 1500 bps
- console.log('接口数据不完整,使用默认码率: 1500 bps');
- return 800;
- }
- },
- // 回放、预告缓冲
- getInternetTraffic() {
- if (!this.liveId || !this.liveId || !this.userData.userId || !this.uuId) return;
- const currentTime = (this.stayTime / this.liveItem.duration) * 100;
- const param = {
- videoType: this.liveItem.videoType,
- videoId: this.liveItem.videoId,
- userId: this.userData.userId,
- liveId: this.liveId,
- uuId: dayjs().format('YYYYMMDD') + this.uuId,
- duration: this.liveItem.duration,
- bufferRate: currentTime
- };
- if (this.liveItem.status == 1) {
- param.videoType = this.liveItem.previewVideoType || '';
- param.videoId = this.liveItem.previewVideoId || '';
- }
- if (this.liveItem.liveType == 1) {
- param.bufferRate = this.totalTraffic;
- }
- internetTraffic(param);
- },
- saveVideoProgress() {
- if (this.videoProgressKey) {
- uni.setStorage({
- key: this.videoProgressKey,
- data: this.videoCurrentTime,
- success: () => {},
- fail: (err) => {
- console.error('保存视频进度失败:', err);
- }
- });
- }
- },
- getTimeDifferenceInSeconds(createTimeStr) {
- const createTime = new Date(createTimeStr.replace(/-/g, '/'));
- const now = new Date();
- const timeDiffMs = now - createTime;
- const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
- return Math.max(0, timeDiffSeconds);
- },
- // onVideoWaiting(e) {
- // // console.log('视频等待加载', e);
- // if (this.liveItem.liveType == 2) {
- // this.startTrafficCalculation(this.bitrate);
- // } else {
- // let that = this;
- // if (this.trafficInterval) {
- // clearInterval(this.trafficInterval);
- // this.trafficInterval = null;
- // }
- // this.trafficInterval = setInterval(function() {
- // that.getInternetTraffic();
- // }, 10000);
- // }
- // },
- onVideoWaiting(e) {
- // console.log('视频等待加载', e);
- if (this.liveItem.liveType == 2) {
- // 修改这里:不再传入固定码率,而是在方法内部计算
- this.startTrafficCalculation();
- } else {
- let that = this;
- if (this.trafficInterval) {
- clearInterval(this.trafficInterval);
- this.trafficInterval = null;
- }
- this.trafficInterval = setInterval(function() {
- that.getInternetTraffic();
- }, 10000);
- }
- },
- setVideoProgress() {
- // 只有录播和回放需要设置进度
- if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
- return;
- }
- let currentTime = 0;
- if (this.liveItem.liveType === 2) {
- // 录播:计算当前时间与开始时间的差值,对视频总时长取模
- const diff = this.getTimeDifferenceInSeconds(this.liveItem.startTime);
- if (diff > this.liveItem.duration) {
- console.log("开始断点续播了")
- const storedProgress = uni.getStorageSync(this.videoProgressKey) || 0;
- console.log("开始断点续播了storedProgress", storedProgress)
- currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
- console.log("开始断点续播了currentTime", currentTime)
- } else {
- currentTime = diff % this.liveItem.duration;
- }
- // currentTime = diff % this.liveItem.duration;
- } else if (this.liveItem.liveType === 3) {
- // 回放:从存储中获取进度
- const storedProgress = uni.getStorageSync(this.videoProgressKey);
- currentTime = storedProgress || 0;
- }
- const videoId = `myVideo_${this.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (videoContext) {
- videoContext.seek(currentTime);
- }
- }, // 视频播放
- onVideoPlay(e) {},
- // 录播时间点
- onVideoMetaLoaded(e) {
- console.log("录播时间点", e)
- this.videoProgressKey = `videoProgress_${this.liveId}`;
- this.setVideoProgress();
- },
- // 视频时间更新
- onVideoTimeUpdate(e) {
- // 获取当前播放时间
- this.videoCurrentTime = e.detail.currentTime;
- // 每隔10秒保存一次进度(避免频繁存储)
- if (Math.floor(this.videoCurrentTime) % 10 === 0) {
- this.saveVideoProgress();
- }
- },
- // 初始化组件 - 增强版本
- async initializeComponent() {
- console.log('初始化视频组件:', {
- liveId: this.liveId,
- liveItem: this.liveItem,
- 状态: this.liveItem?.status,
- 开始时间: this.liveItem?.startTime
- });
- this.uuId = generateRandomString(16);
- this.isAgreement = uni.getStorageSync('isAgreement');
- // 立即检查当前状态并启动相应功能
- if (this.liveItem?.status === 1 && this.liveItem.startTime) {
- console.log('检测到预告状态,立即启动倒计时');
- this.startLiveCountdown();
- } else if (this.liveItem?.status === 2) {
- this.startTimeTimer(this.liveItem);
- this.playVideo();
- }
- this.startTimer();
- this.hasInitialized = true;
- },
- // 启动直播倒计时 - 增强版本
- startLiveCountdown() {
- console.log('启动直播倒计时:', this.liveItem.startTime);
- // 清理旧定时器
- if (this.liveStartTimer) {
- clearInterval(this.liveStartTimer);
- this.liveStartTimer = null;
- }
- // 立即计算一次倒计时
- this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
- console.log('初始倒计时:', this.liveCountdown);
- // 如果倒计时已结束,触发直播开始事件
- if (!this.liveCountdown) {
- console.log('倒计时已结束,触发直播开始');
- this.$emit('liveStart');
- return;
- }
- // 启动定时器
- this.liveStartTimer = setInterval(() => {
- const previousCountdown = JSON.stringify(this.liveCountdown);
- this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
- // 记录倒计时变化(用于调试)
- if (previousCountdown !== JSON.stringify(this.liveCountdown)) {
- console.log('倒计时更新:', this.liveCountdown);
- }
- if (!this.liveCountdown) {
- console.log('倒计时结束,触发直播开始');
- this.$emit('liveStart');
- clearInterval(this.liveStartTimer);
- this.liveStartTimer = null;
- }
- }, 1000);
- },
- // 时间处理函数 - 增强错误处理
- handleTime(time, duration) {
- if (!time) {
- console.error('时间参数为空');
- return false;
- }
- let timeStamp;
- try {
- if (typeof time === 'number' && time > 0 && time < 9999999999999) {
- timeStamp = time;
- } else if (typeof time === 'string' && time.trim() !== '') {
- const isoTime = time.replace(' ', 'T');
- const date = new Date(isoTime);
- if (!isNaN(date.getTime())) {
- timeStamp = date.getTime();
- } else {
- console.error('无效的日期格式:', time);
- return false;
- }
- } else {
- console.error('time参数必须是有效的时间戳或日期字符串');
- return false;
- }
- const targetTimestamp = timeStamp + duration * 60 * 1000;
- const currentTimestamp = Date.now();
- const timeDiffMs = targetTimestamp - currentTimestamp;
- if (timeDiffMs <= 0) {
- return false;
- }
- const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
- const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
- const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);
- const formatNum = (num) => num.toString().padStart(2, '0');
- return {
- hours: formatNum(hours),
- minutes: formatNum(minutes),
- seconds: formatNum(seconds),
- rawMs: timeDiffMs // 添加原始毫秒数用于调试
- };
- } catch (error) {
- console.error('时间处理错误:', error);
- return false;
- }
- },
- // 其他方法保持不变...
- startTimeTimer(item) {
- if (!item) return;
- this.calculateTimeDiff(item);
- if (item.timeTimer) {
- clearInterval(item.timeTimer);
- }
- item.timeTimer = setInterval(() => {
- this.calculateTimeDiff(item);
- }, 1000);
- },
- calculateTimeDiff(item) {
- if (!item.startTime) return;
- const time = new Date(item.startTime.replace(/-/g, '/'));
- if (isNaN(time.getTime())) return;
- const now = new Date();
- let diffMs = Math.max(0, now.getTime() - time.getTime());
- const totalSeconds = Math.floor(diffMs / 1000);
- const hours = this.padZero(Math.floor(totalSeconds / 3600));
- const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
- const seconds = this.padZero(totalSeconds % 60);
- this.diffTotalTime = `${hours}:${minutes}:${seconds}`;
- },
- padZero(num) {
- return num < 10 ? `0${num}` : num;
- },
- // 清理方法
- cleanup() {
- if (this.liveStartTimer) {
- clearInterval(this.liveStartTimer);
- this.liveStartTimer = null;
- }
- if (this.trafficTimer) {
- clearInterval(this.trafficTimer);
- this.trafficTimer = null;
- }
- if (this.trafficInterval) {
- clearInterval(this.trafficInterval);
- this.trafficInterval = null;
- }
- if (this.lookTimer) {
- clearInterval(this.lookTimer);
- this.lookTimer = null;
- }
- if (this.liveItem && this.liveItem.timeTimer) {
- clearInterval(this.liveItem.timeTimer);
- this.liveItem.timeTimer = null;
- }
- }
- }
- };
- </script>
- <style scoped lang="scss">
- .video-player-container {
- width: 100%;
- height: 100%;
- position: relative;
- }
- .videolist {
- position: relative;
- height: 100vh;
- width: 100%;
- &.screen {
- width: 100%;
- height: 100%;
- }
- .video {
- height: 100vh;
- width: 100%;
- .item {
- width: 100%;
- height: 100%;
- }
- .time {
- color: #ffffff;
- font-size: 20rpx;
- margin-left: 10rpx;
- }
- .look-time {
- position: absolute;
- left: 10vh;
- bottom: 24rpx;
- font-size: 20rpx;
- background-color: rgba(57, 57, 57, 0.6);
- border-radius: 15rpx;
- z-index: 999999 !important;
- padding: 10rpx 16rpx;
- color: #fff;
- }
- .end {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- font-size: 36rpx;
- color: #fff;
- }
- .lable {
- position: absolute;
- top: 50rpx;
- right: 16rpx;
- background-color: rgba(57, 57, 57, 0.6);
- padding: 4rpx 10rpx;
- color: #fff;
- border-radius: 15rpx;
- }
- }
- .video_row {
- position: absolute;
- top: 380rpx;
- max-height: 450rpx;
- z-index: 99;
- /* ==== 全屏模式样式 ==== */
- &.fullscreen-mode {
- // position: fixed !important;
- // top: 0 !important;
- // left: 0 !important;
- top: 0;
- width: 0;
- height: auto;
- z-index: 99999 !important;
- background-color: #000 !important;
- transform: rotate(90deg) !important;
- transform-origin: center center !important;
- // transform: rotate(0) ;
- // transform: rotate(90deg) translateY(-100%) !important;
- // transform-origin: left top !important;
- .item {
- position: absolute;
- bottom: 0;
- width: 100vh !important;
- height: 100vw !important;
- // transform: rotate(-90deg) !important;
- transform-origin: center center !important;
- object-fit: contain !important;
- }
- .custom-controls {
- transform: rotate(-90deg) !important;
- transform-origin: center center !important;
- bottom: auto !important;
- top: 40rpx !important;
- right: 40rpx !important;
- }
- .fullscreen-exit-btn {
- position: fixed;
- bottom: 40rpx;
- left: 82vh;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- z-index: 100001;
- background: rgba(57, 57, 57, 0.6);
- border-radius: 40rpx;
- padding: 20rpx 24rpx;
- transition: all 0.3s ease;
- &:active {
- transform: scale(0.95);
- background: rgba(50, 50, 50, 0.6);
- }
- .exit-fullscreen-icon {
- width: 40rpx;
- height: 40rpx;
- margin-bottom: 10rpx;
- }
- .exit-text {
- color: #ffffff;
- font-size: 22rpx;
- white-space: nowrap;
- }
- }
- }
- /* 全屏按钮样式优化 */
- .custom-controls {
- position: absolute;
- bottom: 10%;
- right: 40rpx;
- z-index: 99999999;
- background: rgba(0, 0, 0, 0.6);
- border-radius: 50%;
- width: 80rpx;
- height: 80rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- transition: all 0.3s ease;
- .control-icon {
- width: 46rpx;
- height: 46rpx;
- }
- &:active {
- transform: scale(0.95);
- background: rgba(0, 0, 0, 0.8);
- }
- }
- }
- }
- // 重置按钮样式
- .button-reset {
- background-color: transparent !important;
- padding: 0 !important;
- line-height: 1 !important;
- margin: 0 !important;
- width: auto !important;
- font-weight: 500 !important;
- border-radius: none !important;
- &::after {
- border: none !important;
- padding: 0 !important;
- margin: 0 !important;
- }
- }
- .trailer-box {
- width: calc(100% - 80rpx);
- background: #333333;
- border-radius: 24rpx;
- position: absolute;
- top: 320rpx;
- left: 50%;
- transform: translateX(-50%);
- display: flex;
- flex-direction: column;
- align-items: center;
- color: #fff;
- padding: 20rpx;
- z-index: 99999;
- box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.12);
- transition: box-shadow 0.3s ease;
- .trailer-video {
- width: 100%;
- height: 400rpx;
- }
- .trailer-placeholder {
- margin-bottom: 40rpx;
- width: 240rpx;
- height: 240rpx;
- }
- .countdown-container {
- margin: 20rpx 0;
- display: flex;
- flex-direction: column;
- align-items: center;
- .live-name {
- font-weight: 600;
- font-size: 36rpx;
- }
- .countdown-display {
- display: flex;
- align-items: center;
- margin: 30rpx 0;
- .countdown-label {
- font-size: 24rpx;
- color: #999999;
- }
- .countdown-separator {
- font-size: 24rpx;
- color: #999999;
- }
- .countdown-unit {
- width: 40rpx;
- height: 40rpx;
- background: #4D4D4D;
- border-radius: 8rpx;
- text-align: center;
- overflow: hidden;
- margin: 0 8rpx;
- font-weight: 500;
- font-size: 28rpx;
- color: #FFFFFF;
- line-height: 40rpx;
- }
- }
- }
- .trailer-actions {
- display: flex;
- justify-content: center;
- align-items: center;
- .action-button {
- width: 280rpx;
- height: 72rpx;
- border-radius: 36rpx;
- line-height: 72rpx;
- text-align: center;
- color: #fff;
- &.reserve-button {
- background: linear-gradient(136deg, #38D97D 0%, #02B176 100%);
- }
- &:not(.reserve-button) {
- background: #F4A007;
- }
- .button-icon {
- width: 32rpx;
- height: 32rpx;
- }
- }
- }
- .no-live-title {
- margin-top: 30rpx;
- font-size: 42rpx;
- font-weight: 500;
- }
- }
- </style>
|