index.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <template>
  2. <view class="content">
  3. <mescroll-body bottom="0" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
  4. :down="downOption" :up="upOption">
  5. <view class="list">
  6. <view class="list-item" @click="goLive(item)" v-for="(item,index) in list" :key="index">
  7. <image v-if="!item._isInView && item.liveImgUrl" :src="item.liveImgUrl"></image>
  8. <!-- 直播流 -->
  9. <video v-if="item._isInView && item.liveType == 1 && item.flvHlsUrl" :id="'myVideo_' + item.liveId"
  10. :src="item.flvHlsUrl" :autoplay="false" :controls="false" object-fit="contain"
  11. :custom-cache="false" :enable-progress-gesture="false" :show-center-play-btn="false"
  12. :http-cache="false" :muted="true" @error="onVideoError(item, $event)"></video>
  13. <!-- 录播视频 -->
  14. <video v-if="item._isInView && item.liveType == 2 && item.videoUrl " :id="'myVideo_' + item.liveId"
  15. :src="item.videoUrl" :autoplay="false" :controls="false" object-fit="contain"
  16. :custom-cache="false" :enable-progress-gesture="false" :show-center-play-btn="false"
  17. :http-cache="false" :loop="true" :muted="true" @error="onVideoError(item, $event)"
  18. @loadedmetadata="onVideoLoaded(item)"></video>
  19. <view class="info">
  20. <!-- <text v-if="item.liveType == 1" class="live-badge">直播</text>
  21. <text v-else class="record-badge">录播</text> -->
  22. <text>{{item.liveName}}</text>
  23. </view>
  24. <!-- 添加错误提示 -->
  25. <!-- <view v-if="item._error" class="error-tip">
  26. 视频加载失败
  27. </view> -->
  28. </view>
  29. </view>
  30. </mescroll-body>
  31. </view>
  32. </template>
  33. <script>
  34. import Hls from 'hls.js';
  35. import {
  36. liveList
  37. } from '@/api/list'
  38. import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
  39. export default {
  40. mixins: [MescrollMixin],
  41. data() {
  42. return {
  43. list: [],
  44. downOption: {
  45. offset: 80,
  46. use: true,
  47. auto: false
  48. },
  49. upOption: {
  50. use: true,
  51. auto: true,
  52. page: {
  53. num: 0,
  54. size: 10
  55. }
  56. },
  57. mescroll: null,
  58. observer: null // 存储IntersectionObserver实例
  59. }
  60. },
  61. onLoad() {
  62. if (!uni.getStorageSync("AppToken")) {
  63. uni.navigateTo({
  64. url: '/pages/auth/login'
  65. });
  66. }
  67. },
  68. onUnload() {
  69. // 清理所有观察器和视频资源
  70. this.cleanupAllVideos();
  71. },
  72. methods: {
  73. // 视频加载错误处理
  74. onVideoError(item, e) {
  75. // console.error('视频加载错误:', e.detail, item);
  76. this.$set(item, '_error', true);
  77. this.pauseVideo(item);
  78. },
  79. // 视频元数据加载完成
  80. onVideoLoaded(item) {
  81. console.log('视频元数据加载完成:', item.liveId);
  82. this.$set(item, '_error', false);
  83. },
  84. // 初始化所有视频观察器
  85. initAllVideoObservers() {
  86. // 先清理旧的
  87. this.cleanupAllVideos();
  88. // 使用setTimeout确保DOM已渲染
  89. setTimeout(() => {
  90. this.list.forEach(item => {
  91. if (item.liveId) {
  92. this.initVideoObserver(item);
  93. }
  94. });
  95. }, 300);
  96. },
  97. // 初始化单个视频的观察器
  98. initVideoObserver(item) {
  99. const videoId = `myVideo_${item.liveId}`;
  100. // 创建交叉观察器(监听视频项是否进入视口)
  101. const observer = uni.createIntersectionObserver(this);
  102. observer.relativeToViewport({
  103. top: 100, // 顶部提前100px触发(优化体验,避免刚进入就播放)
  104. bottom: 100 // 底部延迟100px触发(避免快速滑动时频繁切换)
  105. }).observe(`#${videoId}`, (res) => {
  106. const isInView = res.intersectionRatio > 0; // 是否进入视口(交叉比例>0)
  107. // 1. 动态更新 _isInView 状态(确保响应式)
  108. if (isInView !== item._isInView) {
  109. this.$set(item, '_isInView', isInView);
  110. }
  111. // 2. 联动播放/暂停:进入视口播放,离开暂停
  112. if (isInView) {
  113. this.playVideo(item); // 进入视口:播放视频
  114. } else {
  115. this.pauseVideo(item); // 离开视口:暂停视频
  116. }
  117. });
  118. // 存储观察器引用,便于后续清理
  119. this.$set(item, '_observer', observer);
  120. },
  121. // 播放视频
  122. playVideo(item) {
  123. // 仅当:进入视口(_isInView=true)、未在播放(_isPlaying=false)、无错误(_error=false)时播放
  124. if (!item._isInView || item._isPlaying || item._error) return;
  125. const videoId = `myVideo_${item.liveId}`;
  126. const isLive = item.liveType == 1;
  127. // 获取video上下文
  128. uni.createSelectorQuery().in(this)
  129. .select(`#${videoId}`)
  130. .fields({
  131. context: true
  132. })
  133. .exec((res) => {
  134. if (res && res[0] && res[0].context) {
  135. const videoContext = res[0].context;
  136. try {
  137. if (isLive) {
  138. // 直播流处理
  139. // #ifdef H5
  140. if (item.flvHlsUrl && item.flvHlsUrl.includes('.m3u8') && Hls.isSupported()) {
  141. this.setupHlsPlayback(item, videoContext);
  142. } else {
  143. videoContext.play();
  144. }
  145. //#else
  146. videoContext.play();
  147. //#endif
  148. } else {
  149. // 录播视频处理 - 添加重试机制
  150. const playAttempt = () => {
  151. videoContext.play().then(() => {
  152. console.log('录播视频播放成功:', item.liveId);
  153. this.$set(item, '_isPlaying', true);
  154. this.$set(item, '_videoContext', videoContext);
  155. }).catch(err => {
  156. console.error('录播视频播放失败:', err);
  157. this.$set(item, '_error', true);
  158. });
  159. };
  160. // 如果视频已加载,直接播放;否则监听加载事件
  161. if (videoContext.duration > 0) {
  162. playAttempt();
  163. } else {
  164. videoContext.onloadedmetadata = playAttempt;
  165. }
  166. }
  167. // 播放成功后标记 _isPlaying=true
  168. this.$set(item, '_isPlaying', true);
  169. this.$set(item, '_videoContext', videoContext);
  170. } catch (err) {
  171. console.error(`播放失败 ${videoId}:`, err);
  172. this.$set(item, '_error', true);
  173. }
  174. }
  175. });
  176. },
  177. // 暂停视频
  178. pauseVideo(item) {
  179. if (!item._isPlaying) return;
  180. if (item._videoContext) {
  181. item._videoContext.pause();
  182. }
  183. // 清理HLS实例(如果是直播且使用了HLS)
  184. // #ifdef H5
  185. if (item.liveType == 1 && item._hlsInstance) {
  186. item._hlsInstance.destroy();
  187. this.$set(item, '_hlsInstance', null);
  188. }
  189. //#endif
  190. // 暂停后标记 _isPlaying=false(_isInView 已由视口监听控制)
  191. this.$set(item, '_isPlaying', false);
  192. },
  193. // H5平台的HLS播放设置
  194. // #ifdef H5
  195. setupHlsPlayback(item, videoElement) {
  196. if (item._hlsInstance) {
  197. item._hlsInstance.destroy();
  198. }
  199. const hls = new Hls({
  200. enableWorker: true,
  201. lowLatencyMode: true,
  202. debug: false
  203. });
  204. hls.attachMedia(videoElement);
  205. hls.loadSource(item.flvHlsUrl);
  206. hls.on(Hls.Events.MANIFEST_PARSED, () => {
  207. videoElement.play();
  208. });
  209. this.$set(item, '_hlsInstance', hls);
  210. },
  211. // #endif
  212. // 清理所有视频资源
  213. cleanupAllVideos() {
  214. this.list.forEach(item => {
  215. this.pauseVideo(item);
  216. // 重置视口状态:未进入视口
  217. this.$set(item, '_isInView', false);
  218. // 销毁观察器
  219. if (item._observer) {
  220. item._observer.disconnect();
  221. this.$set(item, '_observer', null);
  222. }
  223. });
  224. },
  225. // mescroll初始化
  226. mescrollInit(mescroll) {
  227. this.mescroll = mescroll;
  228. },
  229. // 下拉刷新回调
  230. downCallback(mescroll) {
  231. this.cleanupAllVideos();
  232. this.list = [];
  233. mescroll.resetUpScroll();
  234. },
  235. // 上拉加载回调
  236. upCallback(mescroll) {
  237. const pageNum = mescroll.num;
  238. const pageSize = mescroll.size;
  239. let data = {
  240. pageSize: pageSize,
  241. page: pageNum,
  242. }
  243. liveList(data).then(res => {
  244. if (res.code == 200) {
  245. let curPageData = res.rows || [];
  246. console.log("curPageData在这里>>>>", curPageData)
  247. let totalSize = res.total || 0;
  248. // 预处理数据,添加状态字段
  249. curPageData = curPageData.map(item => {
  250. return {
  251. ...item,
  252. _error: false,
  253. _isPlaying: false,
  254. _isInView: false // 关键:初始化为未进入视口
  255. };
  256. });
  257. if (pageNum === 1) {
  258. this.list = [];
  259. }
  260. this.list = this.list.concat(curPageData);
  261. console.log("list在这里>>>>", list)
  262. // DOM更新后初始化视频观察器
  263. this.$nextTick(() => {
  264. this.initAllVideoObservers();
  265. });
  266. mescroll.endBySize(curPageData.length, totalSize);
  267. } else {
  268. mescroll.endErr();
  269. uni.showToast({
  270. title: res.msg,
  271. icon: 'none'
  272. });
  273. }
  274. }).catch(err => {
  275. mescroll.endErr();
  276. });
  277. },
  278. goLive(item) {
  279. uni.navigateTo({
  280. url: `/pages/home/living?liveId=${item.liveId}&immediate=true`
  281. });
  282. }
  283. }
  284. }
  285. </script>
  286. <style lang="scss" scoped>
  287. .content {
  288. background-color: #111;
  289. min-height: 100vh;
  290. padding: 24rpx;
  291. .list {
  292. display: flex;
  293. justify-content: space-between;
  294. flex-wrap: wrap;
  295. .list-item {
  296. border-radius: 16rpx;
  297. width: 340rpx;
  298. height: 600rpx;
  299. background-color: #0d0d0d;
  300. margin-bottom: 24rpx;
  301. overflow: hidden;
  302. position: relative;
  303. image {
  304. width: 100%;
  305. height: 100%;
  306. }
  307. video {
  308. width: 100%;
  309. height: 100%;
  310. object-fit: cover;
  311. }
  312. .info {
  313. position: absolute;
  314. left: 20rpx;
  315. bottom: 14rpx;
  316. right: 20rpx;
  317. color: #ffffff;
  318. display: flex;
  319. align-items: center;
  320. .live-badge {
  321. background-color: #e74c3c;
  322. padding: 4rpx 12rpx;
  323. border-radius: 8rpx;
  324. font-size: 20rpx;
  325. margin-right: 12rpx;
  326. }
  327. .record-badge {
  328. background-color: #3498db;
  329. padding: 4rpx 12rpx;
  330. border-radius: 8rpx;
  331. font-size: 20rpx;
  332. margin-right: 12rpx;
  333. }
  334. }
  335. .error-tip {
  336. position: absolute;
  337. top: 50%;
  338. left: 50%;
  339. transform: translate(-50%, -50%);
  340. color: #fff;
  341. background-color: rgba(0, 0, 0, 0.7);
  342. padding: 16rpx 24rpx;
  343. border-radius: 8rpx;
  344. font-size: 24rpx;
  345. }
  346. }
  347. // 使列表项均匀分布
  348. .list-item:nth-child(2n) {
  349. margin-right: 0;
  350. }
  351. }
  352. }
  353. </style>