liveVideo.vue 31 KB

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