liveVideo.vue 33 KB

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