123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388 |
- <template>
- <view class="content">
- <mescroll-body bottom="0" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback"
- :down="downOption" :up="upOption">
- <view class="list">
- <view class="list-item" @click="goLive(item)" v-for="(item,index) in list" :key="index">
- <image v-if="item.liveImgUrl" :src="item.liveImgUrl"></image>
- <!-- 直播流 -->
- <!-- <video v-if=" item.liveType == 1 && item.flvHlsUrl" :id="'myVideo_' + item.liveId"
- :src="item.flvHlsUrl" :autoplay="false" muted :controls="false" object-fit="contain"
- :custom-cache="false" :enable-progress-gesture="false" :show-center-play-btn="false"
- :http-cache="false" :muted="true" @error="onVideoError(item, $event)"></video> -->
- <!-- 录播视频 -->
- <!-- <video v-if=" item.liveType == 2 && item.videoUrl " :id="'myVideo_' + item.liveId"
- :src="item.videoUrl" :autoplay="false" muted :controls="false" object-fit="contain"
- :custom-cache="false" :enable-progress-gesture="false" :show-center-play-btn="false"
- :http-cache="false" :loop="true" :muted="true" @error="onVideoError(item, $event)"
- @loadedmetadata="onVideoLoaded(item)"></video> -->
- <view class="info">
- <text>{{item.liveName}}</text>
- </view>
- </view>
- </view>
- </mescroll-body>
- </view>
- </template>
- <script>
- import Hls from 'hls.js';
- import {
- liveList
- } from '@/api/list'
- import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
- export default {
- mixins: [MescrollMixin],
- data() {
- return {
- list: [],
- downOption: {
- offset: 80,
- use: true,
- auto: false
- },
- upOption: {
- use: true,
- auto: true,
- page: {
- num: 0,
- size: 10
- }
- },
- mescroll: null,
- observer: null // 存储IntersectionObserver实例
- }
- },
- onLoad() {
- if (!uni.getStorageSync("AppToken")) {
- uni.navigateTo({
- url: '/pages/auth/login'
- });
- }
- },
- onUnload() {
- // 清理所有观察器和视频资源
- this.cleanupAllVideos();
- },
- methods: {
- // 视频加载错误处理
- onVideoError(item, e) {
- // console.error('视频加载错误:', e.detail, item);
- this.$set(item, '_error', true);
- this.pauseVideo(item);
- },
- // 视频元数据加载完成
- onVideoLoaded(item) {
- console.log('视频元数据加载完成:', item.liveId);
- this.$set(item, '_error', false);
- },
- // 初始化所有视频观察器
- initAllVideoObservers() {
- // 先清理旧的
- this.cleanupAllVideos();
- // 使用setTimeout确保DOM已渲染
- setTimeout(() => {
- this.list.forEach(item => {
- if (item.liveId) {
- this.initVideoObserver(item);
- }
- });
- }, 300);
- },
- // 初始化单个视频的观察器
- initVideoObserver(item) {
- const videoId = `myVideo_${item.liveId}`;
- // 创建交叉观察器(监听视频项是否进入视口)
- const observer = uni.createIntersectionObserver(this);
- observer.relativeToViewport({
- top: 100, // 顶部提前100px触发(优化体验,避免刚进入就播放)
- bottom: 100 // 底部延迟100px触发(避免快速滑动时频繁切换)
- }).observe(`#${videoId}`, (res) => {
- const isInView = res.intersectionRatio > 0; // 是否进入视口(交叉比例>0)
- // 2. 联动播放/暂停:进入视口播放,离开暂停
- if (isInView) {
- this.playVideo(item); // 进入视口:播放视频
- } else {
- this.pauseVideo(item); // 离开视口:暂停视频
- }
- });
- // 存储观察器引用,便于后续清理
- this.$set(item, '_observer', observer);
- },
- // 播放视频
- playVideo(item) {
-
- if ( item._isPlaying || item._error) return;
- const videoId = `myVideo_${item.liveId}`;
- const isLive = item.liveType == 1;
- // 获取video上下文
- uni.createSelectorQuery().in(this)
- .select(`#${videoId}`)
- .fields({
- context: true
- })
- .exec((res) => {
- if (res && res[0] && res[0].context) {
- const videoContext = res[0].context;
- try {
- if (isLive) {
- // 直播流处理
- // #ifdef H5
- if (item.flvHlsUrl && item.flvHlsUrl.includes('.m3u8') && Hls.isSupported()) {
- this.setupHlsPlayback(item, videoContext);
- } else {
- videoContext.play();
- }
- //#else
- videoContext.play();
- //#endif
- } else {
- // 录播视频处理 - 添加重试机制
- const playAttempt = () => {
- videoContext.play().then(() => {
- console.log('录播视频播放成功:', item.liveId);
- this.$set(item, '_isPlaying', true);
- this.$set(item, '_videoContext', videoContext);
- }).catch(err => {
- console.error('录播视频播放失败:', err);
- this.$set(item, '_error', true);
- });
- };
- // 如果视频已加载,直接播放;否则监听加载事件
- if (videoContext.duration > 0) {
- playAttempt();
- } else {
- videoContext.onloadedmetadata = playAttempt;
- }
- }
- // 播放成功后标记 _isPlaying=true
- this.$set(item, '_isPlaying', true);
- this.$set(item, '_videoContext', videoContext);
- } catch (err) {
- console.error(`播放失败 ${videoId}:`, err);
- this.$set(item, '_error', true);
- }
- }
- });
- },
- // 暂停视频
- pauseVideo(item) {
- if (!item._isPlaying) return;
- if (item._videoContext) {
- item._videoContext.pause();
- }
- // 清理HLS实例(如果是直播且使用了HLS)
- // #ifdef H5
- if (item.liveType == 1 && item._hlsInstance) {
- item._hlsInstance.destroy();
- this.$set(item, '_hlsInstance', null);
- }
- //#endif
- this.$set(item, '_isPlaying', false);
- },
- // H5平台的HLS播放设置
- // #ifdef H5
- setupHlsPlayback(item, videoElement) {
- if (item._hlsInstance) {
- item._hlsInstance.destroy();
- }
- const hls = new Hls({
- enableWorker: true,
- lowLatencyMode: true,
- debug: false
- });
- hls.attachMedia(videoElement);
- hls.loadSource(item.flvHlsUrl);
- hls.on(Hls.Events.MANIFEST_PARSED, () => {
- videoElement.play();
- });
- this.$set(item, '_hlsInstance', hls);
- },
- // #endif
- // 清理所有视频资源
- cleanupAllVideos() {
- this.list.forEach(item => {
- this.pauseVideo(item);
-
- // 销毁观察器
- if (item._observer) {
- item._observer.disconnect();
- this.$set(item, '_observer', null);
- }
- });
- },
- // mescroll初始化
- mescrollInit(mescroll) {
- this.mescroll = mescroll;
- },
- // 下拉刷新回调
- downCallback(mescroll) {
- this.cleanupAllVideos();
- this.list = [];
- mescroll.resetUpScroll();
- },
- // 上拉加载回调
- upCallback(mescroll) {
- const pageNum = mescroll.num;
- const pageSize = mescroll.size;
- let data = {
- pageSize: pageSize,
- pageNum: pageNum,
- }
- liveList(data).then(res => {
- if (res.code == 200) {
- let curPageData = res.rows || [];
- // console.log("curPageData在这里>>>>", res)
- let totalSize = res.total || 0;
- // 预处理数据,添加状态字段
- curPageData = curPageData.map(item => {
- return {
- ...item,
- _error: false,
- _isPlaying: false,
- };
- });
- if (pageNum === 1) {
- this.list = [];
- }
- this.list = this.list.concat(curPageData);
- // DOM更新后初始化视频观察器
- this.$nextTick(() => {
- this.initAllVideoObservers();
- });
- mescroll.endBySize(curPageData.length, totalSize);
- } else {
- mescroll.endErr();
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- }).catch(err => {
- mescroll.endErr();
- });
- },
- goLive(item) {
- uni.navigateTo({
- url: `/pages/home/living?liveId=${item.liveId}&immediate=true`
- });
- }
- }
- }
- </script>
- <style lang="scss" scoped>
- .content {
- background-color: #111;
- min-height: 100vh;
- padding: 24rpx;
- .list {
- display: flex;
- justify-content: space-between;
- flex-wrap: wrap;
- .list-item {
- border-radius: 16rpx;
- width: 340rpx;
- height: 600rpx;
- background-color: #0d0d0d;
- margin-bottom: 24rpx;
- overflow: hidden;
- position: relative;
- image {
- width: 100%;
- height: 100%;
- }
- video {
- width: 100%;
- height: 100%;
- object-fit: cover;
- }
- .info {
- position: absolute;
- left: 20rpx;
- bottom: 14rpx;
- right: 20rpx;
- color: #ffffff;
- display: flex;
- align-items: center;
- .live-badge {
- background-color: #e74c3c;
- padding: 4rpx 12rpx;
- border-radius: 8rpx;
- font-size: 20rpx;
- margin-right: 12rpx;
- }
- .record-badge {
- background-color: #3498db;
- padding: 4rpx 12rpx;
- border-radius: 8rpx;
- font-size: 20rpx;
- margin-right: 12rpx;
- }
- }
- .error-tip {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- color: #fff;
- background-color: rgba(0, 0, 0, 0.7);
- padding: 16rpx 24rpx;
- border-radius: 8rpx;
- font-size: 24rpx;
- }
- }
- // 使列表项均匀分布
- .list-item:nth-child(2n) {
- margin-right: 0;
- }
- }
- }
- </style>
|