liveVideo-new.vue 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. // 逻辑学
  361. // this.liveItem.liveType === 1
  362. // this.liveItem.livingUrl='https://live.test.ifeiyu100.com/live/133.flv?txSecret=d95f28727acac2800e9aee9cef98858d&txTime=6943A264'
  363. // this.liveItem.status == 2
  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. calculateBitrate() {
  545. // 如果接口返回了视频文件大小和时长,使用这些数据计算码率
  546. if (this.liveItem.videoFileSize && this.liveItem.videoDuration) {
  547. // 码率 = 文件大小(字节) / 时长(秒) × 8 (转换为bps)
  548. return (this.liveItem.videoFileSize / this.liveItem.videoDuration) * 8;
  549. } else {
  550. // 默认值
  551. return this.liveItem.liveType === 1 ? 1600 : 800;
  552. }
  553. },
  554. calculateAndSubmitTraffic() {
  555. if (!this.liveItem || !this.liveItem.videoFileSize) return;
  556. const watchDuration = Math.floor((Date.now() - this.trafficStartTime) / 1000);
  557. const totalDuration = this.liveItem.videoDuration || this.liveItem.duration || 0;
  558. const videoFileSize = this.liveItem.videoFileSize || 0;
  559. if (totalDuration <= 0 || videoFileSize <= 0) return;
  560. // 精确计算流量
  561. const traffic = (watchDuration / totalDuration) * videoFileSize;
  562. this.totalTraffic = traffic;
  563. // 提交流量数据
  564. this.submitTraffic(watchDuration);
  565. },
  566. submitTraffic(watchDuration) {
  567. const totalDuration = this.liveItem.videoDuration || this.liveItem.duration || 0;
  568. const videoFileSize = this.liveItem.videoFileSize || 0;
  569. if (totalDuration <= 0 || videoFileSize <= 0) return;
  570. const traffic = (watchDuration / totalDuration) * videoFileSize;
  571. const param = {
  572. userId: this.userData.userId || '',
  573. liveId: this.liveId || '',
  574. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  575. internetTraffic: Math.round(traffic),
  576. watchDuration: watchDuration,
  577. totalDuration: totalDuration,
  578. videoFileSize: videoFileSize
  579. };
  580. liveInternetTraffic(param).catch(err => {
  581. console.error('流量数据提交失败:', err);
  582. });
  583. },
  584. // 回放、预告缓冲
  585. getInternetTraffic() {
  586. if (!this.liveId || !this.liveId || !this.userData.userId || !this.uuId) return;
  587. const currentTime = (this.stayTime / this.liveItem.duration) * 100;
  588. const param = {
  589. videoType: this.liveItem.videoType,
  590. videoId: this.liveItem.videoId,
  591. userId: this.userData.userId,
  592. liveId: this.liveId,
  593. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  594. duration: this.liveItem.duration,
  595. bufferRate: currentTime
  596. };
  597. if (this.liveItem.status == 1) {
  598. param.videoType = this.liveItem.previewVideoType || '';
  599. param.videoId = this.liveItem.previewVideoId || '';
  600. }
  601. if (this.liveItem.liveType == 1) {
  602. param.bufferRate = this.totalTraffic;
  603. }
  604. internetTraffic(param);
  605. },
  606. saveVideoProgress() {
  607. if (this.videoProgressKey) {
  608. uni.setStorage({
  609. key: this.videoProgressKey,
  610. data: this.videoCurrentTime,
  611. success: () => {},
  612. fail: (err) => {
  613. console.error('保存视频进度失败:', err);
  614. }
  615. });
  616. }
  617. },
  618. getTimeDifferenceInSeconds(createTimeStr) {
  619. const createTime = new Date(createTimeStr.replace(/-/g, '/'));
  620. const now = new Date();
  621. const timeDiffMs = now - createTime;
  622. const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
  623. return Math.max(0, timeDiffSeconds);
  624. },
  625. // onVideoWaiting(e) {
  626. // // console.log('视频等待加载', e);
  627. // if (this.liveItem.liveType == 2) {
  628. // this.startTrafficCalculation(this.bitrate);
  629. // } else {
  630. // let that = this;
  631. // if (this.trafficInterval) {
  632. // clearInterval(this.trafficInterval);
  633. // this.trafficInterval = null;
  634. // }
  635. // this.trafficInterval = setInterval(function() {
  636. // that.getInternetTraffic();
  637. // }, 10000);
  638. // }
  639. // },
  640. onVideoWaiting(e) {
  641. // console.log('视频等待加载', e);
  642. if (this.liveItem.liveType == 2) {
  643. // 修改这里:不再传入固定码率,而是在方法内部计算
  644. this.startTrafficCalculation();
  645. } else {
  646. let that = this;
  647. if (this.trafficInterval) {
  648. clearInterval(this.trafficInterval);
  649. this.trafficInterval = null;
  650. }
  651. this.trafficInterval = setInterval(function() {
  652. that.getInternetTraffic();
  653. }, 10000);
  654. }
  655. },
  656. setVideoProgress() {
  657. // 只有录播和回放需要设置进度
  658. if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
  659. return;
  660. }
  661. let currentTime = 0;
  662. if (this.liveItem.liveType === 2) {
  663. // 录播:计算当前时间与开始时间的差值,对视频总时长取模
  664. const diff = this.getTimeDifferenceInSeconds(this.liveItem.startTime);
  665. if (diff > this.liveItem.duration) {
  666. console.log("开始断点续播了")
  667. const storedProgress = uni.getStorageSync(this.videoProgressKey) || 0;
  668. console.log("开始断点续播了storedProgress", storedProgress)
  669. currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
  670. console.log("开始断点续播了currentTime", currentTime)
  671. } else {
  672. currentTime = diff % this.liveItem.duration;
  673. }
  674. // currentTime = diff % this.liveItem.duration;
  675. } else if (this.liveItem.liveType === 3) {
  676. // 回放:从存储中获取进度
  677. const storedProgress = uni.getStorageSync(this.videoProgressKey);
  678. currentTime = storedProgress || 0;
  679. }
  680. const videoId = `myVideo_${this.liveId}`;
  681. const videoContext = uni.createVideoContext(videoId, this);
  682. if (videoContext) {
  683. videoContext.seek(currentTime);
  684. }
  685. }, // 视频播放
  686. onVideoPlay(e) {},
  687. // 录播时间点
  688. onVideoMetaLoaded(e) {
  689. console.log("录播时间点", e)
  690. this.videoProgressKey = `videoProgress_${this.liveId}`;
  691. this.setVideoProgress();
  692. },
  693. // 视频时间更新
  694. onVideoTimeUpdate(e) {
  695. // 获取当前播放时间
  696. this.videoCurrentTime = e.detail.currentTime;
  697. // 每隔10秒保存一次进度(避免频繁存储)
  698. if (Math.floor(this.videoCurrentTime) % 10 === 0) {
  699. this.saveVideoProgress();
  700. }
  701. },
  702. // 初始化组件 - 增强版本
  703. async initializeComponent() {
  704. console.log('初始化视频组件:', {
  705. liveId: this.liveId,
  706. liveItem: this.liveItem,
  707. 状态: this.liveItem?.status,
  708. 开始时间: this.liveItem?.startTime
  709. });
  710. this.uuId = generateRandomString(16);
  711. this.isAgreement = uni.getStorageSync('isAgreement');
  712. // 立即检查当前状态并启动相应功能
  713. if (this.liveItem?.status === 1 && this.liveItem.startTime) {
  714. console.log('检测到预告状态,立即启动倒计时');
  715. this.startLiveCountdown();
  716. } else if (this.liveItem?.status === 2) {
  717. this.startTimeTimer(this.liveItem);
  718. this.playVideo();
  719. }
  720. this.startTimer();
  721. this.hasInitialized = true;
  722. },
  723. // 启动直播倒计时 - 增强版本
  724. startLiveCountdown() {
  725. console.log('启动直播倒计时:', this.liveItem.startTime);
  726. // 清理旧定时器
  727. if (this.liveStartTimer) {
  728. clearInterval(this.liveStartTimer);
  729. this.liveStartTimer = null;
  730. }
  731. // 立即计算一次倒计时
  732. this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
  733. console.log('初始倒计时:', this.liveCountdown);
  734. // 如果倒计时已结束,触发直播开始事件
  735. if (!this.liveCountdown) {
  736. console.log('倒计时已结束,触发直播开始');
  737. this.$emit('liveStart');
  738. return;
  739. }
  740. // 启动定时器
  741. this.liveStartTimer = setInterval(() => {
  742. const previousCountdown = JSON.stringify(this.liveCountdown);
  743. this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
  744. // 记录倒计时变化(用于调试)
  745. if (previousCountdown !== JSON.stringify(this.liveCountdown)) {
  746. console.log('倒计时更新:', this.liveCountdown);
  747. }
  748. if (!this.liveCountdown) {
  749. console.log('倒计时结束,触发直播开始');
  750. this.$emit('liveStart');
  751. clearInterval(this.liveStartTimer);
  752. this.liveStartTimer = null;
  753. }
  754. }, 1000);
  755. },
  756. // 时间处理函数 - 增强错误处理
  757. handleTime(time, duration) {
  758. if (!time) {
  759. console.error('时间参数为空');
  760. return false;
  761. }
  762. let timeStamp;
  763. try {
  764. if (typeof time === 'number' && time > 0 && time < 9999999999999) {
  765. timeStamp = time;
  766. } else if (typeof time === 'string' && time.trim() !== '') {
  767. const isoTime = time.replace(' ', 'T');
  768. const date = new Date(isoTime);
  769. if (!isNaN(date.getTime())) {
  770. timeStamp = date.getTime();
  771. } else {
  772. console.error('无效的日期格式:', time);
  773. return false;
  774. }
  775. } else {
  776. console.error('time参数必须是有效的时间戳或日期字符串');
  777. return false;
  778. }
  779. const targetTimestamp = timeStamp + duration * 60 * 1000;
  780. const currentTimestamp = Date.now();
  781. const timeDiffMs = targetTimestamp - currentTimestamp;
  782. if (timeDiffMs <= 0) {
  783. return false;
  784. }
  785. const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
  786. const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
  787. const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);
  788. const formatNum = (num) => num.toString().padStart(2, '0');
  789. return {
  790. hours: formatNum(hours),
  791. minutes: formatNum(minutes),
  792. seconds: formatNum(seconds),
  793. rawMs: timeDiffMs // 添加原始毫秒数用于调试
  794. };
  795. } catch (error) {
  796. console.error('时间处理错误:', error);
  797. return false;
  798. }
  799. },
  800. // 其他方法保持不变...
  801. startTimeTimer(item) {
  802. if (!item) return;
  803. this.calculateTimeDiff(item);
  804. if (item.timeTimer) {
  805. clearInterval(item.timeTimer);
  806. }
  807. item.timeTimer = setInterval(() => {
  808. this.calculateTimeDiff(item);
  809. }, 1000);
  810. },
  811. calculateTimeDiff(item) {
  812. if (!item.startTime) return;
  813. const time = new Date(item.startTime.replace(/-/g, '/'));
  814. if (isNaN(time.getTime())) return;
  815. const now = new Date();
  816. let diffMs = Math.max(0, now.getTime() - time.getTime());
  817. const totalSeconds = Math.floor(diffMs / 1000);
  818. const hours = this.padZero(Math.floor(totalSeconds / 3600));
  819. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
  820. const seconds = this.padZero(totalSeconds % 60);
  821. this.diffTotalTime = `${hours}:${minutes}:${seconds}`;
  822. },
  823. padZero(num) {
  824. return num < 10 ? `0${num}` : num;
  825. },
  826. // 清理方法
  827. cleanup() {
  828. if (this.liveStartTimer) {
  829. clearInterval(this.liveStartTimer);
  830. this.liveStartTimer = null;
  831. }
  832. if (this.trafficTimer) {
  833. clearInterval(this.trafficTimer);
  834. this.trafficTimer = null;
  835. }
  836. if (this.trafficInterval) {
  837. clearInterval(this.trafficInterval);
  838. this.trafficInterval = null;
  839. }
  840. if (this.lookTimer) {
  841. clearInterval(this.lookTimer);
  842. this.lookTimer = null;
  843. }
  844. if (this.liveItem && this.liveItem.timeTimer) {
  845. clearInterval(this.liveItem.timeTimer);
  846. this.liveItem.timeTimer = null;
  847. }
  848. }
  849. }
  850. };
  851. </script>
  852. <style scoped lang="scss">
  853. .video-player-container {
  854. width: 100%;
  855. height: 100%;
  856. position: relative;
  857. }
  858. .videolist {
  859. position: relative;
  860. height: 100vh;
  861. width: 100%;
  862. .video {
  863. height: 100vh;
  864. width: 100%;
  865. .item {
  866. width: 100%;
  867. height: 100%;
  868. }
  869. .time {
  870. color: #ffffff;
  871. font-size: 20rpx;
  872. margin-left: 10rpx;
  873. }
  874. .end {
  875. position: absolute;
  876. top: 50%;
  877. left: 50%;
  878. transform: translate(-50%, -50%);
  879. font-size: 36rpx;
  880. color: #fff;
  881. }
  882. .lable {
  883. position: absolute;
  884. top: 50rpx;
  885. right: 16rpx;
  886. background-color: rgba(57, 57, 57, 0.6);
  887. padding: 4rpx 10rpx;
  888. color: #fff;
  889. border-radius: 15rpx;
  890. }
  891. }
  892. .video_row {
  893. position: absolute;
  894. top: 380rpx;
  895. max-height: 450rpx;
  896. z-index: 99;
  897. .fullscreen-mode {
  898. width: auto !important;
  899. height: auto !important;
  900. z-index: 99999 !important;
  901. background-color: #000 !important;
  902. transform: rotate(90deg) !important;
  903. transform-origin: center center !important;
  904. .fullscreen-exit-btn {
  905. z-index: 999999 !important;
  906. }
  907. .video-player {
  908. width: 100vh !important;
  909. height: 100vw !important;
  910. // object-fit: contain !important;
  911. }
  912. }
  913. /* 全屏时隐藏其他元素 */
  914. .video-container.fullscreen-mode~* {
  915. display: none !important;
  916. }
  917. /* 全屏按钮样式优化 */
  918. .custom-controls {
  919. position: absolute;
  920. // top: 50%;
  921. bottom: 10%;
  922. right: 40rpx;
  923. z-index: 99999999;
  924. background: rgba(0, 0, 0, 0.6);
  925. border-radius: 50%;
  926. width: 80rpx;
  927. height: 80rpx;
  928. display: flex;
  929. align-items: center;
  930. justify-content: center;
  931. transition: all 0.3s ease;
  932. .control-icon {
  933. width: 46rpx;
  934. height: 46rpx;
  935. }
  936. &:active {
  937. transform: scale(0.95);
  938. background: rgba(0, 0, 0, 0.8);
  939. }
  940. }
  941. }
  942. }
  943. // 重置按钮样式
  944. .button-reset {
  945. background-color: transparent !important;
  946. padding: 0 !important;
  947. line-height: 1 !important;
  948. margin: 0 !important;
  949. width: auto !important;
  950. font-weight: 500 !important;
  951. border-radius: none !important;
  952. &::after {
  953. border: none !important;
  954. padding: 0 !important;
  955. margin: 0 !important;
  956. }
  957. }
  958. .trailer-box {
  959. width: calc(100% - 80rpx);
  960. background: #333333;
  961. border-radius: 24rpx;
  962. position: absolute;
  963. top: 320rpx;
  964. left: 50%;
  965. transform: translateX(-50%);
  966. display: flex;
  967. flex-direction: column;
  968. align-items: center;
  969. color: #fff;
  970. padding: 20rpx;
  971. z-index: 99999;
  972. box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.12);
  973. transition: box-shadow 0.3s ease;
  974. .trailer-video {
  975. width: 100%;
  976. height: 400rpx;
  977. }
  978. .trailer-placeholder {
  979. margin-bottom: 40rpx;
  980. width: 240rpx;
  981. height: 240rpx;
  982. }
  983. .countdown-container {
  984. margin: 20rpx 0;
  985. display: flex;
  986. flex-direction: column;
  987. align-items: center;
  988. .live-name {
  989. font-weight: 600;
  990. font-size: 36rpx;
  991. }
  992. .countdown-display {
  993. display: flex;
  994. align-items: center;
  995. margin: 30rpx 0;
  996. .countdown-label {
  997. font-size: 24rpx;
  998. color: #999999;
  999. }
  1000. .countdown-separator {
  1001. font-size: 24rpx;
  1002. color: #999999;
  1003. }
  1004. .countdown-unit {
  1005. width: 40rpx;
  1006. height: 40rpx;
  1007. background: #4D4D4D;
  1008. border-radius: 8rpx;
  1009. text-align: center;
  1010. overflow: hidden;
  1011. margin: 0 8rpx;
  1012. font-weight: 500;
  1013. font-size: 28rpx;
  1014. color: #FFFFFF;
  1015. line-height: 40rpx;
  1016. }
  1017. }
  1018. }
  1019. .trailer-actions {
  1020. display: flex;
  1021. justify-content: center;
  1022. align-items: center;
  1023. .action-button {
  1024. width: 280rpx;
  1025. height: 72rpx;
  1026. border-radius: 36rpx;
  1027. line-height: 72rpx;
  1028. text-align: center;
  1029. color: #fff;
  1030. &.reserve-button {
  1031. background: linear-gradient(136deg, #38D97D 0%, #02B176 100%);
  1032. }
  1033. &:not(.reserve-button) {
  1034. background: #F4A007;
  1035. }
  1036. .button-icon {
  1037. width: 32rpx;
  1038. height: 32rpx;
  1039. }
  1040. }
  1041. }
  1042. .no-live-title {
  1043. margin-top: 30rpx;
  1044. font-size: 42rpx;
  1045. font-weight: 500;
  1046. }
  1047. }
  1048. </style>