liveVideo.vue 33 KB

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