liveVideo.vue 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. <template>
  2. <view class="video-player-container">
  3. <!-- 直播状态显示 -->
  4. <view class="videolist" v-if="liveItem.status == 2" :class="isFullscreen ? 'screen' : ''">
  5. <view class="video" :class="{'video_row': liveItem.showType == 1,'fullscreen-mode': isFullscreen}">
  6. <!-- 直播 -->
  7. <live-player v-if="liveItem.livingUrl && liveItem.liveType == 1" :id="'myLivePlayer_' + liveId"
  8. :src="liveItem.livingUrl" autoplay mode="live" object-fit="cover" :muted="false"
  9. orientation="vertical" :enable-play-gesture="false" min-cache="1" max-cache="3"
  10. @statechange="onLiveStateChange" @error="onLiveError" class="item"></live-player>
  11. <!-- 录播 -->
  12. <video v-if="liveItem.videoUrl && liveItem.liveType == 2" :id="`myVideo_${liveId}`" :autoplay="true"
  13. class="item" :src="liveItem.videoUrl" :controls="false"
  14. :object-fit="liveItem.showType==2||isFullscreen?'contain':'fill'" :custom-cache="false"
  15. :enable-progress-gesture="false" vslide-gesture-in-fullscreen="false" :show-center-play-btn="false"
  16. :http-cache="false" loop @error="videoError" @timeupdate="onVideoTimeUpdate"
  17. @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
  18. @waiting="onVideoWaiting" :enable-play-gesture="false" :play-strategy="1"
  19. @dblclick="preventDoubleClick" preload="auto" :enable-stash-buffer="false" :stash-initial-size="0"
  20. :stash-max-size="0" :stash-time="0" type="application/x-mpegURL"></video>
  21. <view v-if="liveItem.videoUrl && liveItem.liveType == 2" class="time"
  22. :class="isFullscreen ? 'look-time' : 'time'">{{ diffTotalTime }}</view>
  23. <view class="custom-controls" @click.stop="toggleFullscreen">
  24. <image src="/static/images/full_screen.png" class="control-icon" />
  25. </view>
  26. <!-- 全屏返回按钮 - 只在全屏状态下显示 -->
  27. <view v-if="isFullscreen" class="fullscreen-exit-btn" @click="exitFullscreen">
  28. <image src="/static/images/half_screen.png" class="exit-fullscreen-icon" />
  29. <text class="exit-text">退出全屏</text>
  30. </view>
  31. </view>
  32. </view>
  33. <!-- 直播结束状态 -->
  34. <view class="videolist" v-if="liveItem.status == 3">
  35. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  36. <view class="end">直播已结束</view>
  37. </view>
  38. </view>
  39. <!-- 直播回放状态 -->
  40. <view class="videolist" v-if="liveItem.status == 4">
  41. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  42. <!-- 直播回放 -->
  43. <video v-if="liveItem.videoUrl && liveItem.liveType == 3" :id="`myVideo_${liveId}`" class="item"
  44. :src="liveItem.videoUrl" :autoplay="true" :controls="true" object-fit="cover" :custom-cache="false"
  45. :enable-progress-gesture="liveItem.isSpeedAllowed" vslide-gesture-in-fullscreen="true"
  46. :show-center-play-btn="true" :http-cache="false" loop @error="videoError"
  47. @timeupdate="onVideoTimeUpdate" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause"
  48. @play="onVideoPlay" :enable-play-gesture="true" preload="auto" @waiting="onVideoWaiting"
  49. type="application/x-mpegURL"></video>
  50. <view v-if="liveItem.videoUrl && liveItem.liveType == 3" class="lable">直播回放</view>
  51. </view>
  52. </view>
  53. <view class="trailer-box" v-if="liveItem.status == 1">
  54. <video v-if="liveItem.previewUrl" :id="`myVideo_${liveId}`" class="trailer-video" :src="liveItem.previewUrl"
  55. :autoplay="true" loop object-fit="cover" :custom-cache="false" :enable-progress-gesture="false"
  56. vslide-gesture-in-fullscreen="false" :show-center-play-btn="false" :http-cache="false"
  57. @error="videoError" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
  58. :disable-progress="true" :enable-play-gesture="true" @waiting="onVideoWaiting" preload="auto"
  59. type="application/x-mpegURL" :controls="false"></video>
  60. <image v-if="liveItem.status == 1 && !liveItem.previewUrl" class="trailer-placeholder"
  61. src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/no_live.png">
  62. </image>
  63. <view class="countdown-container" v-if="liveItem.status == 1 && liveCountdown">
  64. <view class="live-name">{{ liveItem.liveName }}</view>
  65. <view class="countdown-display">
  66. <text class="countdown-label">距离开播还有</text>
  67. <view class="countdown-unit">
  68. {{ liveCountdown.hours || '00' }}
  69. </view>
  70. <view class="countdown-separator">:</view>
  71. <view class="countdown-unit">
  72. {{ liveCountdown.minutes || '00' }}
  73. </view>
  74. <view class="countdown-separator">:</view>
  75. <view class="countdown-unit">
  76. {{ liveCountdown.seconds || '00' }}
  77. </view>
  78. </view>
  79. </view>
  80. <view class="trailer-actions">
  81. <button open-type="share" class="button-reset share-button">
  82. <view class="action-button mr18" @click="handleAgreement">
  83. <text>分享给好友</text>
  84. </view>
  85. </button>
  86. <view class="action-button reserve-button" @click="handleAgreement">
  87. <image class="button-icon mr8" src="/static/images/trailer.png"></image>
  88. <text>{{ hasSubscribed ? '已预约' : '预约直播'}}</text>
  89. <!-- <text>预约直播</text> -->
  90. </view>
  91. </view>
  92. </view>
  93. <!-- 无直播状态 -->
  94. <view class="trailer-box" v-if="!liveItem">
  95. <image class="img" src="/static/images/no_live.png"></image>
  96. <view class="title">暂无直播</view>
  97. </view>
  98. </view>
  99. </template>
  100. <script>
  101. import {
  102. generateRandomString
  103. } from '@/utils/common.js';
  104. import dayjs from 'dayjs';
  105. import {
  106. internetTraffic,
  107. liveInternetTraffic
  108. } from '@/api/living.js';
  109. import {
  110. getUserInfo
  111. } from '@/api/user';
  112. export default {
  113. name: 'LiveVideoPlayer',
  114. props: {
  115. liveItem: {
  116. type: Object,
  117. default: () => ({})
  118. },
  119. liveId: {
  120. type: [String, Number],
  121. default: ''
  122. },
  123. userData: {
  124. type: Object,
  125. default: () => ({})
  126. },
  127. isAgreement: {
  128. type: Boolean,
  129. default: false
  130. },
  131. hasSubscribed: {
  132. type: Boolean,
  133. default: false
  134. }
  135. },
  136. data() {
  137. return {
  138. videoLoaded: false, // 视频是否加载成功
  139. isManualPause: false, // 是否手动暂停
  140. waitingTimer: null, // 视频等待定时器
  141. waitingStartTime: 0, // 视频等待开始时间
  142. lastVideoUpdateTime: 0, // 视频最后更新时间
  143. trafficStartTime: 0, // 流量计算开始时间
  144. liveBeginWatchTime: 0, //开始观看的时间点 不包含预告
  145. // hasSubscribed: false, // 已成功订阅(永久禁用)
  146. isFullscreen: false,
  147. isVideoRotated: false,
  148. showNonVideoElementsFlag: true,
  149. showCustomControls: true,
  150. videoContext: null,
  151. // 流量计算相关
  152. uuId: '',
  153. totalTraffic: 0,
  154. bitrate: 800,
  155. bitrateLive: 1600,
  156. // 定时器
  157. trafficTimer: null,
  158. liveStartTimer: null,
  159. trafficInterval: null,
  160. lookTimer: null,
  161. // 状态数据
  162. liveCountdown: {},
  163. diffTotalTime: '',
  164. videoCurrentTime: 0,
  165. videoProgressKey: '',
  166. startTime: 0,
  167. stayTime: 0,
  168. // 内部状态跟踪
  169. hasInitialized: false,
  170. lastLiveItemStatus: null
  171. };
  172. },
  173. watch: {
  174. // 深度监听 liveItem 的所有变化
  175. liveItem: {
  176. handler(newVal, oldVal) {
  177. if (newVal && newVal.status === 1 && newVal.startTime) {
  178. // 如果是预告状态且有开始时间,立即启动倒计时
  179. this.startLiveCountdown();
  180. }
  181. },
  182. deep: true,
  183. immediate: true // 立即执行一次
  184. },
  185. // 单独监听 status 变化作为备用
  186. 'liveItem.status': {
  187. handler(newStatus, oldStatus) {
  188. console.log('状态变化:', oldStatus, '->', newStatus);
  189. if (newStatus === 1 && this.liveItem.startTime) {
  190. this.startLiveCountdown();
  191. } else if (newStatus === 2) {
  192. this.startTimeTimer(this.liveItem);
  193. }
  194. },
  195. immediate: true
  196. }
  197. },
  198. async created() {
  199. // 最早的可执行时机
  200. if (this.liveItem && Object.keys(this.liveItem).length > 0) {
  201. await this.initializeComponent();
  202. }
  203. },
  204. // async mounted() {
  205. // await this.initializeComponent();
  206. // },
  207. computed: {
  208. shouldShowNonVideoElements() {
  209. return !this.isFullscreen && this.showNonVideoElementsFlag;
  210. },
  211. // 控制是否显示全屏按钮
  212. shouldShowFullscreenButton() {
  213. return this.liveItem.showType == 1 && !this.isFullscreen;
  214. },
  215. },
  216. beforeUnmount() {
  217. this.cleanup();
  218. // 强制退出全屏
  219. this.isFullscreen = false;
  220. this.showCustomControls = true;
  221. },
  222. methods: {
  223. // 退出全屏
  224. exitFullscreen() {
  225. console.log('执行退出全屏');
  226. this.isFullscreen = false;
  227. // 显示非videolist元素
  228. this.showNonVideoElements();
  229. // 强制页面重排
  230. this.$nextTick(() => {
  231. this.$forceUpdate();
  232. this.$emit('fullscreen-change', this.isFullscreen);
  233. });
  234. },
  235. // 恢复videolist盒子
  236. restoreVideoList() {
  237. this.isVideoRotated = false;
  238. this.isFullscreen = false;
  239. },
  240. // 切换全屏
  241. toggleFullscreen() {
  242. // console.log('自定义全屏按钮被点击');
  243. if (this.isFullscreen) {
  244. // 退出全屏
  245. this.exitFullscreen();
  246. } else {
  247. // 进入全屏
  248. this.enterFullscreen();
  249. }
  250. }, // 进入全屏
  251. enterFullscreen() {
  252. console.log('执行进入全屏');
  253. this.isFullscreen = true;
  254. // 设置横屏样式
  255. this.rotateVideoList();
  256. // 隐藏非videolist元素
  257. this.hideNonVideoElements();
  258. this.$emit('fullscreen-change', this.isFullscreen);
  259. // 强制页面重排
  260. this.$forceUpdate();
  261. },
  262. // 隐藏非videolist元素
  263. hideNonVideoElements() {
  264. this.showNonVideoElementsFlag = false;
  265. console.log('隐藏非视频元素');
  266. },
  267. // 显示非videolist元素
  268. showNonVideoElements() {
  269. this.showNonVideoElementsFlag = true;
  270. },
  271. // 防止默认全屏事件
  272. onFullscreenChange(e) {
  273. // 阻止默认全屏行为
  274. e.preventDefault();
  275. // 如果有video进入全屏,立即退出
  276. if (e.detail && e.detail.fullScreen) {
  277. const videoContext = uni.createVideoContext(`myVideo_${this.liveId}`, this);
  278. if (videoContext) {
  279. setTimeout(() => {
  280. videoContext.exitFullScreen();
  281. }, 100);
  282. }
  283. }
  284. },
  285. // 旋转videolist盒子
  286. rotateVideoList() {
  287. this.isVideoRotated = true;
  288. this.isFullscreen = true;
  289. console.log('视频容器旋转到横屏状态');
  290. },
  291. // 全屏状态变化监听
  292. onFullscreenChange(e) {
  293. console.log('全屏状态变化事件详情:', e);
  294. // 方法1:通过事件参数获取(小程序主要方式)
  295. let fullScreen = false;
  296. // 视频组件的全屏事件参数
  297. if (e.detail && typeof e.detail.fullScreen !== 'undefined') {
  298. fullScreen = e.detail.fullScreen;
  299. console.log('通过e.detail.fullScreen获取全屏状态:', fullScreen);
  300. }
  301. // 其他可能的参数名
  302. else if (e.detail && typeof e.detail.fullscreen !== 'undefined') {
  303. fullScreen = e.detail.fullscreen;
  304. console.log('通过e.detail.fullscreen获取全屏状态:', fullScreen);
  305. }
  306. // 方法2:检测横屏(备用)
  307. else {
  308. // 在小程序环境中,可以通过屏幕方向判断
  309. try {
  310. const systemInfo = uni.getSystemInfoSync();
  311. fullScreen = systemInfo.windowWidth > systemInfo.windowHeight;
  312. console.log('通过屏幕方向判断全屏状态:', fullScreen);
  313. } catch (err) {
  314. console.error('获取系统信息失败:', err);
  315. // 默认使用事件参数
  316. fullScreen = e.detail || false;
  317. }
  318. }
  319. this.isFullscreen = fullScreen;
  320. console.log('最终设置isFullscreen为:', this.isFullscreen);
  321. // 根据全屏状态显示/隐藏自定义控件
  322. this.showCustomControls = !this.isFullscreen;
  323. // 强制UI更新
  324. this.$forceUpdate();
  325. // 全屏时锁定横屏
  326. if (this.isFullscreen) {
  327. this.lockOrientation();
  328. } else {
  329. this.unlockOrientation();
  330. }
  331. },
  332. // 锁定屏幕方向为横屏
  333. lockOrientation() {
  334. // 设置屏幕方向为横屏
  335. try {
  336. // 尝试锁定横屏
  337. plus.screen.lockOrientation('landscape-primary');
  338. } catch (e) {
  339. console.log('锁定屏幕方向失败:', e);
  340. // 备用方案
  341. try {
  342. // 使用 Web API(如果支持)
  343. if (screen.orientation && screen.orientation.lock) {
  344. screen.orientation.lock('landscape');
  345. }
  346. } catch (err) {
  347. console.log('备用方案也失败了:', err);
  348. }
  349. }
  350. }, // 解锁屏幕方向
  351. unlockOrientation() {
  352. try {
  353. plus.screen.unlockOrientation();
  354. } catch (e) {
  355. console.log('解锁屏幕方向失败:', e);
  356. // 备用方案
  357. try {
  358. if (screen.orientation && screen.orientation.unlock) {
  359. screen.orientation.unlock();
  360. }
  361. } catch (err) {
  362. console.log('备用解锁方案也失败了:', err);
  363. }
  364. }
  365. },
  366. handleAgreement() {
  367. console.log('预约直播点击');
  368. this.$emit('agreementClick');
  369. }, // 播放视频
  370. playVideo() {
  371. if (!this.liveItem) {
  372. console.log('liveItem 为空,无法播放视频');
  373. return;
  374. }
  375. try {
  376. // 直播流使用live-player
  377. if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
  378. const livePlayerId = `myLivePlayer_${this.liveId}`;
  379. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  380. // console.log("直播")
  381. if (livePlayerContext) {
  382. livePlayerContext.play();
  383. }
  384. } else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
  385. const videoId = `myVideo_${this.liveId}`;
  386. const videoContext = uni.createVideoContext(videoId, this);
  387. if (videoContext) {
  388. videoContext.play();
  389. }
  390. } else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem.status == 2) {
  391. const videoId = `myVideo_${this.liveId}`;
  392. const videoContext = uni.createVideoContext(videoId, this);
  393. // console.log("录播")
  394. if (videoContext) {
  395. videoContext.play();
  396. }
  397. } // 回放视频使用video
  398. else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem.status == 4) {
  399. const videoId = `myVideo_${this.liveId}`;
  400. const videoContext = uni.createVideoContext(videoId, this);
  401. // console.log("回放")
  402. if (videoContext) {
  403. videoContext.play();
  404. }
  405. }
  406. } catch (error) {
  407. console.error('播放视频失败:', error);
  408. }
  409. },
  410. pauseVideo() {
  411. if (!this.liveItem) return;
  412. try {
  413. // 直播流使用live-player
  414. if (this.liveItem.status == 1) {
  415. const videoId = `myVideo_${this.liveId}`;
  416. const videoContext = uni.createVideoContext(videoId, this);
  417. if (videoContext) {
  418. videoContext.pause();
  419. }
  420. } else if (this.liveItem.status == 2) {
  421. if (this.liveItem.liveType === 1) {
  422. const livePlayerId = `myLivePlayer_${this.liveId}`;
  423. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  424. if (livePlayerContext) {
  425. livePlayerContext.pause();
  426. }
  427. } else if (this.liveItem.liveType === 2) {
  428. const videoId = `myVideo_${this.liveId}`;
  429. const videoContext = uni.createVideoContext(videoId, this);
  430. if (videoContext) {
  431. videoContext.pause();
  432. }
  433. }
  434. }
  435. } catch (error) {
  436. console.error('暂停视频失败:', error);
  437. }
  438. },
  439. // 视频错误处理
  440. videoError(e, liveItem) {
  441. if (!liveItem || !this.liveId) return;
  442. // 初始化重试计数
  443. if (this.videoRetryCounts[liveItem.liveId] === undefined) {
  444. this.videoRetryCounts[liveItem.liveId] = 0;
  445. }
  446. // 限制重试次数
  447. if (this.videoRetryCounts[liveItem.liveId] >= 3) {
  448. console.error(`直播间 ${this.liveId} 视频加载失败,停止重试`);
  449. // 显示错误提示
  450. uni.showToast({
  451. title: '视频加载失败,请检查网络',
  452. icon: 'none',
  453. duration: 2000
  454. });
  455. return;
  456. }
  457. this.videoRetryCounts[this.liveId]++;
  458. // 延迟重试
  459. setTimeout(() => {
  460. if (this.liveId === this.liveId) {
  461. console.log(`第${this.videoRetryCounts[this.liveId]}次重试播放视频`);
  462. this.playVideo();
  463. }
  464. }, 2000);
  465. }, // 视频暂停
  466. onVideoPause(e) {
  467. if (this.liveItem.liveType === 2) {
  468. const videoId = `myVideo_${this.liveId}`;
  469. const videoContext = uni.createVideoContext(videoId, this);
  470. setTimeout(() => {
  471. videoContext.play();
  472. }, 100);
  473. }
  474. // 暂停时保存进度
  475. this.saveVideoProgress();
  476. }, //直播、录播缓冲
  477. getLiveInternetTraffic() {
  478. if (!this.liveId) return;
  479. const currentTime = (this.stayTime / this.liveItem.duration) * 100;
  480. const param = {
  481. userId: this.userData.userId || '',
  482. liveId: this.liveId || '',
  483. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  484. internetTraffic: this.totalTraffic
  485. };
  486. liveInternetTraffic(param);
  487. },
  488. startTimer() {
  489. this.startTime = Date.now();
  490. this.lookTimer = setInterval(() => {
  491. this.stayTime = Math.floor((Date.now() - this.startTime) / 1000);
  492. }, 1000);
  493. },
  494. // 计算流量
  495. // calculateTraffic(bitrate) {
  496. // const currentTime = Date.now();
  497. // const duration = (currentTime - this.startTime) / 1000; // 持续时间(秒)
  498. // // 流量 = 码率 × 时间
  499. // // 码率单位: bps, 时间单位: 秒, 流量单位: 比特
  500. // const trafficBits = bitrate * duration;
  501. // // 转换为字节
  502. // this.totalTraffic = trafficBits / 8;
  503. // this.getLiveInternetTraffic();
  504. // },
  505. // 计算流量
  506. calculateTraffic(bitrate) {
  507. const currentTime = Date.now();
  508. const duration = (currentTime - this.startTime) / 1000; // 持续时间(秒)
  509. // 流量 = 码率 × 时间
  510. // 码率单位: bps, 时间单位: 秒, 流量单位: 比特
  511. const trafficBits = bitrate * duration;
  512. // 转换为字节
  513. this.totalTraffic = trafficBits / 8;
  514. // 调用流量上报接口
  515. this.getLiveInternetTraffic();
  516. },
  517. //直播计算流量
  518. // startTrafficCalculation(bitrate) {
  519. // if (this.trafficTimer) {
  520. // clearInterval(this.trafficTimer);
  521. // this.trafficTimer = null;
  522. // }
  523. // this.startTime = Date.now();
  524. // var that = this;
  525. // this.trafficTimer = setInterval(() => {
  526. // that.calculateTraffic(bitrate);
  527. // }, 10000); // 每10秒计算一次
  528. // },
  529. startTrafficCalculation() {
  530. if (this.trafficTimer) {
  531. clearInterval(this.trafficTimer);
  532. this.trafficTimer = null;
  533. }
  534. this.startTime = Date.now();
  535. var that = this;
  536. // 计算码率
  537. let bitrate = this.calculateBitrate();
  538. this.trafficTimer = setInterval(() => {
  539. that.calculateTraffic(bitrate);
  540. }, 10000); // 每10秒计算一次
  541. }, // 计算码率
  542. calculateBitrate() {
  543. // 如果接口返回了视频文件大小和时长,使用这些数据计算码率
  544. if (this.liveItem.videoFileSize && this.liveItem.videoDuration) {
  545. // 码率 = 文件大小(字节) / 时长(秒) × 8 (转换为bps) × 5
  546. const calculatedBitrate = (this.liveItem.videoFileSize / this.liveItem.videoDuration) * 8 * 5;
  547. console.log(
  548. `使用接口数据计算码率: ${calculatedBitrate} bps (文件大小: ${this.liveItem.videoFileSize} 字节, 时长: ${this.liveItem.videoDuration} 秒)`
  549. );
  550. return calculatedBitrate;
  551. } else {
  552. // 如果任一字段为空,使用默认码率 1500 bps
  553. console.log('接口数据不完整,使用默认码率: 1500 bps');
  554. return 800;
  555. }
  556. },
  557. // 回放、预告缓冲
  558. getInternetTraffic() {
  559. if (!this.liveId || !this.liveId || !this.userData.userId || !this.uuId) return;
  560. const currentTime = (this.stayTime / this.liveItem.duration) * 100;
  561. const param = {
  562. videoType: this.liveItem.videoType,
  563. videoId: this.liveItem.videoId,
  564. userId: this.userData.userId,
  565. liveId: this.liveId,
  566. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  567. duration: this.liveItem.duration,
  568. bufferRate: currentTime
  569. };
  570. if (this.liveItem.status == 1) {
  571. param.videoType = this.liveItem.previewVideoType || '';
  572. param.videoId = this.liveItem.previewVideoId || '';
  573. }
  574. if (this.liveItem.liveType == 1) {
  575. param.bufferRate = this.totalTraffic;
  576. }
  577. internetTraffic(param);
  578. },
  579. saveVideoProgress() {
  580. if (this.videoProgressKey) {
  581. uni.setStorage({
  582. key: this.videoProgressKey,
  583. data: this.videoCurrentTime,
  584. success: () => {},
  585. fail: (err) => {
  586. console.error('保存视频进度失败:', err);
  587. }
  588. });
  589. }
  590. },
  591. getTimeDifferenceInSeconds(createTimeStr, useServerTime) {
  592. // 参数检查,确保createTimeStr不为undefined或null
  593. if (!createTimeStr) {
  594. return 0;
  595. }
  596. const createTime = new Date(String(createTimeStr).replace(/-/g, '/'));
  597. const now = new Date();
  598. const timeDiffMs = now - createTime;
  599. const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
  600. return Math.max(0, timeDiffSeconds);
  601. },
  602. // onVideoWaiting(e) {
  603. // // console.log('视频等待加载', e);
  604. // if (this.liveItem.liveType == 2) {
  605. // this.startTrafficCalculation(this.bitrate);
  606. // } else {
  607. // let that = this;
  608. // if (this.trafficInterval) {
  609. // clearInterval(this.trafficInterval);
  610. // this.trafficInterval = null;
  611. // }
  612. // this.trafficInterval = setInterval(function() {
  613. // that.getInternetTraffic();
  614. // }, 10000);
  615. // }
  616. // },
  617. onVideoWaiting(e) {
  618. // console.log('视频等待加载', e);
  619. if (this.liveItem.liveType == 2) {
  620. // 修改这里:不再传入固定码率,而是在方法内部计算
  621. this.startTrafficCalculation();
  622. } else {
  623. let that = this;
  624. if (this.trafficInterval) {
  625. clearInterval(this.trafficInterval);
  626. this.trafficInterval = null;
  627. }
  628. this.trafficInterval = setInterval(function() {
  629. that.getInternetTraffic();
  630. }, 10000);
  631. }
  632. },
  633. setVideoProgress() {
  634. // 只有录播和回放需要设置进度
  635. if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
  636. return;
  637. }
  638. let currentTime = 0;
  639. if (this.liveItem.liveType === 2) {
  640. // 录播:计算当前时间与开始时间的差值,对视频总时长取模
  641. const diff = this.getTimeDifferenceInSeconds(this.liveItem.startTime);
  642. if (diff > this.liveItem.duration) {
  643. console.log("开始断点续播了")
  644. const storedProgress = uni.getStorageSync(this.videoProgressKey) || 0;
  645. console.log("开始断点续播了storedProgress", storedProgress)
  646. currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
  647. console.log("开始断点续播了currentTime", currentTime)
  648. } else {
  649. currentTime = diff % this.liveItem.duration;
  650. }
  651. // currentTime = diff % this.liveItem.duration;
  652. } else if (this.liveItem.liveType === 3) {
  653. // 回放:从存储中获取进度
  654. const storedProgress = uni.getStorageSync(this.videoProgressKey);
  655. currentTime = storedProgress || 0;
  656. }
  657. const videoId = `myVideo_${this.liveId}`;
  658. const videoContext = uni.createVideoContext(videoId, this);
  659. if (videoContext) {
  660. videoContext.seek(currentTime);
  661. }
  662. }, // 视频播放
  663. onVideoPlay(e) {
  664. //console.log("qxj onVideoPlay");
  665. // 重置手动暂停标志
  666. this.isManualPause = false;
  667. // 清除等待定时器
  668. if (this.waitingTimer) {
  669. clearTimeout(this.waitingTimer);
  670. this.waitingTimer = null;
  671. }
  672. this.waitingStartTime = 0;
  673. this.lastVideoUpdateTime = Date.now(); // 更新最后更新时间
  674. if (this.liveItem.status == 2) {
  675. //this.startCountdown();
  676. // 启动观看时长统计
  677. //this.startWatchDurationTracking();
  678. }
  679. if (this.watchTimeTimer) {
  680. clearInterval(this.watchTimeTimer);
  681. this.watchTimeTimer = null;
  682. this.saveWatchTime();
  683. console.log("视频开始播放")
  684. }
  685. },
  686. // 录播时间点
  687. onVideoMetaLoaded(e) {
  688. console.log("录播时间点", e)
  689. this.videoProgressKey = `videoProgress_${this.liveId}`;
  690. this.setVideoProgress();
  691. },
  692. // 视频时间更新
  693. onVideoTimeUpdate(e) {
  694. // 获取当前播放时间
  695. this.videoCurrentTime = e.detail.currentTime;
  696. // 每隔10秒保存一次进度(避免频繁存储)
  697. if (Math.floor(this.videoCurrentTime) % 10 === 0) {
  698. this.saveVideoProgress();
  699. }
  700. // 更新视频最后更新时间(用于检测是否卡顿)
  701. this.lastVideoUpdateTime = Date.now();
  702. // 如果视频在更新,说明没有卡顿,清除等待状态
  703. if (this.waitingStartTime && this.lastVideoUpdateTime - this.waitingStartTime < 1000) {
  704. // 视频在1秒内恢复了,清除等待定时器
  705. if (this.waitingTimer) {
  706. clearTimeout(this.waitingTimer);
  707. this.waitingTimer = null;
  708. }
  709. this.waitingStartTime = 0;
  710. }
  711. // 使用服务器时间判断直播是否结束
  712. const diff = this.getTimeDifferenceInSeconds(this.liveItem.serviceStartTime, true)
  713. if (diff >= this.liveItem.duration) {
  714. if (!this.hasPlayback) {
  715. this.generating = false;
  716. this.hasPlayback = true;
  717. this.isEnd = true;
  718. }
  719. }
  720. },
  721. // 初始化组件 - 增强版本
  722. async initializeComponent() {
  723. console.log('初始化视频组件:', {
  724. liveId: this.liveId,
  725. liveItem: this.liveItem,
  726. 状态: this.liveItem?.status,
  727. 开始时间: this.liveItem?.startTime
  728. });
  729. this.uuId = generateRandomString(16);
  730. this.isAgreement = uni.getStorageSync('isAgreement');
  731. // 立即检查当前状态并启动相应功能
  732. if (this.liveItem?.status === 1 && this.liveItem.startTime) {
  733. console.log('检测到预告状态,立即启动倒计时');
  734. this.startLiveCountdown();
  735. } else if (this.liveItem?.status === 2) {
  736. this.startTimeTimer(this.liveItem);
  737. this.playVideo();
  738. }
  739. this.startTimer();
  740. this.hasInitialized = true;
  741. },
  742. // 启动直播倒计时 - 增强版本
  743. startLiveCountdown() {
  744. console.log('启动直播倒计时:', this.liveItem.startTime);
  745. // 清理旧定时器
  746. if (this.liveStartTimer) {
  747. clearInterval(this.liveStartTimer);
  748. this.liveStartTimer = null;
  749. }
  750. // 立即计算一次倒计时
  751. this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
  752. console.log('初始倒计时:', this.liveCountdown);
  753. // 如果倒计时已结束,触发直播开始事件
  754. if (!this.liveCountdown) {
  755. console.log('倒计时已结束,触发直播开始');
  756. this.$emit('liveStart');
  757. return;
  758. }
  759. // 启动定时器
  760. this.liveStartTimer = setInterval(() => {
  761. const previousCountdown = JSON.stringify(this.liveCountdown);
  762. this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
  763. // 记录倒计时变化(用于调试)
  764. if (previousCountdown !== JSON.stringify(this.liveCountdown)) {
  765. console.log('倒计时更新:', this.liveCountdown);
  766. }
  767. if (!this.liveCountdown) {
  768. console.log('倒计时结束,触发直播开始');
  769. this.$emit('liveStart');
  770. clearInterval(this.liveStartTimer);
  771. this.liveStartTimer = null;
  772. }
  773. }, 1000);
  774. },
  775. // 时间处理函数 - 增强错误处理
  776. handleTime(time, duration) {
  777. if (!time) {
  778. console.error('时间参数为空');
  779. return false;
  780. }
  781. let timeStamp;
  782. try {
  783. if (typeof time === 'number' && time > 0 && time < 9999999999999) {
  784. timeStamp = time;
  785. } else if (typeof time === 'string' && time.trim() !== '') {
  786. const isoTime = time.replace(' ', 'T');
  787. const date = new Date(isoTime);
  788. if (!isNaN(date.getTime())) {
  789. timeStamp = date.getTime();
  790. } else {
  791. console.error('无效的日期格式:', time);
  792. return false;
  793. }
  794. } else {
  795. console.error('time参数必须是有效的时间戳或日期字符串');
  796. return false;
  797. }
  798. const targetTimestamp = timeStamp + duration * 60 * 1000;
  799. const currentTimestamp = Date.now();
  800. const timeDiffMs = targetTimestamp - currentTimestamp;
  801. if (timeDiffMs <= 0) {
  802. return false;
  803. }
  804. const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
  805. const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
  806. const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);
  807. const formatNum = (num) => num.toString().padStart(2, '0');
  808. return {
  809. hours: formatNum(hours),
  810. minutes: formatNum(minutes),
  811. seconds: formatNum(seconds),
  812. rawMs: timeDiffMs // 添加原始毫秒数用于调试
  813. };
  814. } catch (error) {
  815. console.error('时间处理错误:', error);
  816. return false;
  817. }
  818. },
  819. // 其他方法保持不变...
  820. startTimeTimer(item) {
  821. if (!item) return;
  822. this.calculateTimeDiff(item);
  823. if (item.timeTimer) {
  824. clearInterval(item.timeTimer);
  825. }
  826. item.timeTimer = setInterval(() => {
  827. this.calculateTimeDiff(item);
  828. }, 1000);
  829. },
  830. calculateTimeDiff(item) {
  831. if (!item.startTime) return;
  832. const time = new Date(item.startTime.replace(/-/g, '/'));
  833. if (isNaN(time.getTime())) return;
  834. const now = new Date();
  835. let diffMs = Math.max(0, now.getTime() - time.getTime());
  836. const totalSeconds = Math.floor(diffMs / 1000);
  837. const hours = this.padZero(Math.floor(totalSeconds / 3600));
  838. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
  839. const seconds = this.padZero(totalSeconds % 60);
  840. this.diffTotalTime = `${hours}:${minutes}:${seconds}`;
  841. },
  842. padZero(num) {
  843. return num < 10 ? `0${num}` : num;
  844. },
  845. // 清理方法
  846. cleanup() {
  847. if (this.liveStartTimer) {
  848. clearInterval(this.liveStartTimer);
  849. this.liveStartTimer = null;
  850. }
  851. if (this.trafficTimer) {
  852. clearInterval(this.trafficTimer);
  853. this.trafficTimer = null;
  854. }
  855. if (this.trafficInterval) {
  856. clearInterval(this.trafficInterval);
  857. this.trafficInterval = null;
  858. }
  859. if (this.lookTimer) {
  860. clearInterval(this.lookTimer);
  861. this.lookTimer = null;
  862. }
  863. if (this.liveItem && this.liveItem.timeTimer) {
  864. clearInterval(this.liveItem.timeTimer);
  865. this.liveItem.timeTimer = null;
  866. }
  867. }
  868. }
  869. };
  870. </script>
  871. <style scoped lang="scss">
  872. .video-player-container {
  873. width: 100%;
  874. height: 100%;
  875. position: relative;
  876. }
  877. .videolist {
  878. position: relative;
  879. height: 100vh;
  880. width: 100%;
  881. &.screen {
  882. width: 100%;
  883. height: 100%;
  884. }
  885. .video {
  886. height: 100vh;
  887. width: 100%;
  888. .item {
  889. width: 100%;
  890. height: 100%;
  891. }
  892. .time {
  893. color: #ffffff;
  894. font-size: 20rpx;
  895. margin-left: 10rpx;
  896. }
  897. .look-time {
  898. position: absolute;
  899. left: 10vh;
  900. bottom: 24rpx;
  901. font-size: 20rpx;
  902. background-color: rgba(57, 57, 57, 0.6);
  903. border-radius: 15rpx;
  904. z-index: 999999 !important;
  905. padding: 10rpx 16rpx;
  906. color: #fff;
  907. }
  908. .end {
  909. position: absolute;
  910. top: 50%;
  911. left: 50%;
  912. transform: translate(-50%, -50%);
  913. font-size: 36rpx;
  914. color: #fff;
  915. }
  916. .lable {
  917. position: absolute;
  918. top: 50rpx;
  919. right: 16rpx;
  920. background-color: rgba(57, 57, 57, 0.6);
  921. padding: 4rpx 10rpx;
  922. color: #fff;
  923. border-radius: 15rpx;
  924. }
  925. }
  926. .video_row {
  927. position: absolute;
  928. top: 380rpx;
  929. max-height: 450rpx;
  930. z-index: 99;
  931. /* ==== 全屏模式样式 ==== */
  932. &.fullscreen-mode {
  933. // position: fixed !important;
  934. // top: 0 !important;
  935. // left: 0 !important;
  936. top: 0;
  937. width: 0;
  938. height: auto;
  939. z-index: 99999 !important;
  940. background-color: #000 !important;
  941. transform: rotate(90deg) !important;
  942. transform-origin: center center !important;
  943. // transform: rotate(0) ;
  944. // transform: rotate(90deg) translateY(-100%) !important;
  945. // transform-origin: left top !important;
  946. .item {
  947. position: absolute;
  948. bottom: 0;
  949. width: 100vh !important;
  950. height: 100vw !important;
  951. // transform: rotate(-90deg) !important;
  952. transform-origin: center center !important;
  953. object-fit: contain !important;
  954. }
  955. .custom-controls {
  956. transform: rotate(-90deg) !important;
  957. transform-origin: center center !important;
  958. bottom: auto !important;
  959. top: 40rpx !important;
  960. right: 40rpx !important;
  961. }
  962. .fullscreen-exit-btn {
  963. position: fixed;
  964. bottom: 40rpx;
  965. left: 82vh;
  966. display: flex;
  967. flex-direction: column;
  968. align-items: center;
  969. justify-content: center;
  970. z-index: 100001;
  971. background: rgba(57, 57, 57, 0.6);
  972. border-radius: 40rpx;
  973. padding: 20rpx 24rpx;
  974. transition: all 0.3s ease;
  975. &:active {
  976. transform: scale(0.95);
  977. background: rgba(50, 50, 50, 0.6);
  978. }
  979. .exit-fullscreen-icon {
  980. width: 40rpx;
  981. height: 40rpx;
  982. margin-bottom: 10rpx;
  983. }
  984. .exit-text {
  985. color: #ffffff;
  986. font-size: 22rpx;
  987. white-space: nowrap;
  988. }
  989. }
  990. }
  991. /* 全屏按钮样式优化 */
  992. .custom-controls {
  993. position: absolute;
  994. bottom: 10%;
  995. right: 40rpx;
  996. z-index: 99999999;
  997. background: rgba(0, 0, 0, 0.6);
  998. border-radius: 50%;
  999. width: 80rpx;
  1000. height: 80rpx;
  1001. display: flex;
  1002. align-items: center;
  1003. justify-content: center;
  1004. transition: all 0.3s ease;
  1005. .control-icon {
  1006. width: 46rpx;
  1007. height: 46rpx;
  1008. }
  1009. &:active {
  1010. transform: scale(0.95);
  1011. background: rgba(0, 0, 0, 0.8);
  1012. }
  1013. }
  1014. }
  1015. }
  1016. // 重置按钮样式
  1017. .button-reset {
  1018. background-color: transparent !important;
  1019. padding: 0 !important;
  1020. line-height: 1 !important;
  1021. margin: 0 !important;
  1022. width: auto !important;
  1023. font-weight: 500 !important;
  1024. border-radius: none !important;
  1025. &::after {
  1026. border: none !important;
  1027. padding: 0 !important;
  1028. margin: 0 !important;
  1029. }
  1030. }
  1031. .trailer-box {
  1032. width: calc(100% - 80rpx);
  1033. background: #333333;
  1034. border-radius: 24rpx;
  1035. position: absolute;
  1036. top: 320rpx;
  1037. left: 50%;
  1038. transform: translateX(-50%);
  1039. display: flex;
  1040. flex-direction: column;
  1041. align-items: center;
  1042. color: #fff;
  1043. padding: 20rpx;
  1044. z-index: 99;
  1045. box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.12);
  1046. transition: box-shadow 0.3s ease;
  1047. .trailer-video {
  1048. width: 100%;
  1049. height: 400rpx;
  1050. }
  1051. .trailer-placeholder {
  1052. margin-bottom: 40rpx;
  1053. width: 240rpx;
  1054. height: 240rpx;
  1055. }
  1056. .countdown-container {
  1057. margin: 20rpx 0;
  1058. display: flex;
  1059. flex-direction: column;
  1060. align-items: center;
  1061. .live-name {
  1062. font-weight: 600;
  1063. font-size: 36rpx;
  1064. }
  1065. .countdown-display {
  1066. display: flex;
  1067. align-items: center;
  1068. margin: 30rpx 0;
  1069. .countdown-label {
  1070. font-size: 24rpx;
  1071. color: #999999;
  1072. }
  1073. .countdown-separator {
  1074. font-size: 24rpx;
  1075. color: #999999;
  1076. }
  1077. .countdown-unit {
  1078. width: 40rpx;
  1079. height: 40rpx;
  1080. background: #4D4D4D;
  1081. border-radius: 8rpx;
  1082. text-align: center;
  1083. overflow: hidden;
  1084. margin: 0 8rpx;
  1085. font-weight: 500;
  1086. font-size: 28rpx;
  1087. color: #FFFFFF;
  1088. line-height: 40rpx;
  1089. }
  1090. }
  1091. }
  1092. .trailer-actions {
  1093. display: flex;
  1094. justify-content: center;
  1095. align-items: center;
  1096. .action-button {
  1097. width: 280rpx;
  1098. height: 72rpx;
  1099. display: flex;align-items: center;
  1100. justify-content: center;
  1101. border-radius: 36rpx;
  1102. color: #fff;
  1103. &.reserve-button {
  1104. background: linear-gradient(136deg, #38D97D 0%, #02B176 100%);
  1105. }
  1106. &:not(.reserve-button) {
  1107. background: #F4A007;
  1108. }
  1109. .button-icon {
  1110. width: 32rpx;
  1111. height: 32rpx;
  1112. }
  1113. }
  1114. }
  1115. .no-live-title {
  1116. margin-top: 30rpx;
  1117. font-size: 42rpx;
  1118. font-weight: 500;
  1119. }
  1120. }
  1121. </style>