| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238 |
- <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 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>{{ hasSubscribed ? '已预约' : '预约直播'}}</text>
- <!-- <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
- },
- hasSubscribed: {
- type: Boolean,
- default: false
- }
- },
- data() {
- return {
- videoLoaded: false, // 视频是否加载成功
- isManualPause: false, // 是否手动暂停
- waitingTimer: null, // 视频等待定时器
- waitingStartTime: 0, // 视频等待开始时间
- lastVideoUpdateTime: 0, // 视频最后更新时间
- trafficStartTime: 0, // 流量计算开始时间
- liveBeginWatchTime: 0, //开始观看的时间点 不包含预告
-
- // hasSubscribed: false, // 已成功订阅(永久禁用)
- 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, useServerTime) {
- // 参数检查,确保createTimeStr不为undefined或null
- if (!createTimeStr) {
- return 0;
- }
- const createTime = new Date(String(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) {
- //console.log("qxj onVideoPlay");
- // 重置手动暂停标志
- this.isManualPause = false;
- // 清除等待定时器
- if (this.waitingTimer) {
- clearTimeout(this.waitingTimer);
- this.waitingTimer = null;
- }
- this.waitingStartTime = 0;
- this.lastVideoUpdateTime = Date.now(); // 更新最后更新时间
- if (this.liveItem.status == 2) {
- //this.startCountdown();
- // 启动观看时长统计
- //this.startWatchDurationTracking();
- }
- if (this.watchTimeTimer) {
- clearInterval(this.watchTimeTimer);
- this.watchTimeTimer = null;
- this.saveWatchTime();
- console.log("视频开始播放")
- }
- },
- // 录播时间点
- 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();
- }
- // 更新视频最后更新时间(用于检测是否卡顿)
- this.lastVideoUpdateTime = Date.now();
- // 如果视频在更新,说明没有卡顿,清除等待状态
- if (this.waitingStartTime && this.lastVideoUpdateTime - this.waitingStartTime < 1000) {
- // 视频在1秒内恢复了,清除等待定时器
- if (this.waitingTimer) {
- clearTimeout(this.waitingTimer);
- this.waitingTimer = null;
- }
- this.waitingStartTime = 0;
- }
- // 使用服务器时间判断直播是否结束
- const diff = this.getTimeDifferenceInSeconds(this.liveItem.serviceStartTime, true)
- if (diff >= this.liveItem.duration) {
- if (!this.hasPlayback) {
- this.generating = false;
- this.hasPlayback = true;
- this.isEnd = true;
- }
- }
- },
- // 初始化组件 - 增强版本
- 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: 99;
- 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;
- display: flex;align-items: center;
- justify-content: center;
- border-radius: 36rpx;
- 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>
|