Vue使用EasyPlayerPro播放本地MP4视频

 更新时间:2024年11月29日 10:56:35   作者:前端熊猫  
这篇文章主要为大家详细介绍了Vue如何使用EasyPlayerPro实现播放本地MP4视频功能,感兴趣的小伙伴可以跟随小编一起学习一下

加载本地mp4需指定协议http://localhost:5100/(如 http:、https:、webrtc:、ws: 等)来正确处理媒体流。

目录结构

├── public/
│   ├──static
│   │   ├── video.mp4
├── components/
│   ├── EasyWebRTC.vue
├── views/
│   ├── test/
│   │   ├── index.vue

组件封装

<template>
  <div class="easy-player-container">
    <!-- 为每个播放器容器添加唯一的类 -->
    <div id="player_box1" class="player-box"></div>
  </div>
</template>
 
<script>
/* global EasyPlayerPro */
export default {
  name: 'EasyPlayerPro',
  props: {
    initialConfig: {
      type: Object,
      default: () => ({}),
    },
  },
  data () {
    return {
      player: '',
      playerInstances: {}, // 存储播放器实例
      config: {
        hasAudio: true,
        isLive: true,
        MSE: false,
        WCS: false,
        demuxType: 'auto',
        ...this.initialConfig,
      },
    };
  },
 
 
 
  methods: {
    setVideoUrl (url, id, changeId) {
 
      const resolveUrl = (url) => {
        if (
          url.startsWith('http:') ||
          url.startsWith('https:') ||
          url.startsWith('webrtc:') ||
          url.startsWith('ws:') ||
          url.startsWith('wss:') ||
          url.startsWith('wt:') ||
          url.startsWith('artc:')
        ) {
          return url;
        }
        const baseUrl = `${window.location.protocol}//${window.location.host}`;
        return `${baseUrl}${url}`;
      };
 
      // 转换 URL
      const resolvedUrl = resolveUrl(url);
      console.log(`解析后的 URL: ${resolvedUrl}`);
 
      if (!resolvedUrl) {
        console.error('URL 不能为空');
        return;
      }
 
      // 动态设置 demuxType
      let demuxType = 'auto'; // 默认值
      if (url.endsWith('.mp4')) {
        demuxType = 'mp4';
      } else if (url.startsWith('webrtc://')) {
        demuxType = 'native'; // WebRTC 流
      } else if (url.startsWith('ws://') || url.startsWith('wss://')) {
        demuxType = 'flv'; // WebSocket 流通常为 FLV
      }
      // 更新播放器配置
      this.config = {
        ...this.config,
        demuxType,
        isLive: url.startsWith('webrtc://') || url.includes('live'),
      };
 
 
      const player = this.playerInstances[id];
      if (player) {
        player.play(resolvedUrl).catch((e) => {
          console.error(`播放失败 (播放器${id}):`, e);
          this.$emit('play-error', e);
        });
      } else {
        // 使用箭头函数确保上下文
        this.$nextTick(() => {
          this.createPlayer(id, resolvedUrl);
        });
      }
    },
 
    createPlayer (id, url) {
      const container = document.getElementById(id);
      if (!container) {
        console.error(`未找到容器, ID: ${id}`);
        return;
      }
 
      const player = new EasyPlayerPro(container, {
        demuxType: this.config.demuxType || 'auto',
        autoplay: this.config.autoplay || true,
        muted: this.config.muted || true,
        isLive: this.config.isLive || true,
      });
 
      player
        .play(url)
        .then(() => {
          console.log(`播放成功: ${url}`);
          this.$emit('play-started', id);
        })
        .catch((e) => {
          console.error(`播放失败: ${e.message || e}`, e);
          this.$emit('play-error', { id, error: e });
        });
      // 添加事件监听器:循环播放
      player.on('ended', () => {
        console.log(`播放结束,准备循环播放: ${url}`);
        player.play(url).catch((e) => {
          console.error(`循环播放失败: ${e.message || e}`, e);
        });
      });
      this.playerInstances[id] = player;
      // 添加事件解除静音
      document.addEventListener('click', () => {
        player.unmute(); // 用户交互后解除静音
      });
    },
    // 销毁所有播放器实例
    destroyAllPlayers () {
      Object.keys(this.playerInstances).forEach(id => {
        this.destroyPlayer(id);
      });
    },
    // 销毁单个播放器实例
    destroyPlayer (id) {
      const player = this.playerInstances[id];
      if (player) {
        player.destroy();
        delete this.playerInstances[id];
      }
    },
    handleUnmute () {
      Object.values(this.playerInstances).forEach((player) => {
        if (player) {
          player.unmute();
        }
      });
    },
  },
 
 
 
  beforeUnmount () {
    // 销毁所有播放器实例
    this.destroyAllPlayers();
 
    // 清除全局事件监听器
    document.removeEventListener('click', this.handleUnmute);
  },
 
};
</script>
 
<style scoped>
.easy-player-container {
  width: 100%;
  background: #000;
  height: 100%;
  position: relative;
}
 
 
.player-box {
  background: #000;
}
</style>

应用:

<template>
  <div class="video-content">
    <EasyWebRTC ref="baseVideoRef"
      :initialConfig="{ demuxType: 'native', isLive: false, hasAudio: true, autoplay: true, muted: true }">
    </EasyWebRTC>
    <EasyWebRTC ref="videoRef" :initialConfig="{ demuxType: 'flv', isLive: true, hasAudio: true, }"></EasyWebRTC>
  </div>
</template>
<script setup>
import { ref, onMounted, nextTick } from "vue";
import EasyWebRTC from "../components/EasyWebRTC.vue";
 
// 定义组件引用
const baseVideoRef = ref(null);
const videoRef = ref(null);
 
onMounted(() => {
  nextTick(() => {
    // 配置 baseVideoRef
    if (baseVideoRef.value) {
      const baseVideoUrl = "/video.mp4"; // 替换为实际的视频文件路径
      const baseContainerId = "baseVideo";
 
      try {
        baseVideoRef.value.setVideoUrl(baseVideoUrl, baseContainerId, baseContainerId);
        console.log("baseVideoRef:", baseVideoRef.value);
 
        // 修改 DOM 元素 ID
        const targetChild = baseVideoRef.value.$el?.firstElementChild;
        if (targetChild) {
          targetChild.id = baseContainerId; // 修改 ID
          console.log(`成功修改 baseVideo 的 ID 为: ${baseContainerId}`);
        } else {
          console.warn("未找到 baseVideoRef 的子节点");
        }
      } catch (error) {
        console.error("设置 baseVideo URL 时出错:", error);
      }
    } else {
      console.error("baseVideoRef 未挂载");
    }
 
    // 配置 videoRef
    if (videoRef.value) {
      const videoUrl = "http://sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/mp4/xgplayer-demo-360p.mp4";
      const videoContainerId = "video";
 
      try {
        videoRef.value.setVideoUrl(videoUrl, videoContainerId, videoContainerId);
 
        // 修改父元素中的 ID
        const parentElement = document.querySelector(".video-content");
        if (parentElement) {
          const targetChild = parentElement.querySelector("#player_box1");
          if (targetChild) {
            targetChild.id = videoContainerId; // 修改 ID
            console.log(`成功修改 video 的 ID 为: ${videoContainerId}`);
          } else {
            console.warn("未找到 ID 为 'player_box1' 的子节点");
          }
        } else {
          console.warn("未找到父元素 .video-content");
        }
      } catch (error) {
        console.error("设置 video URL 时出错:", error);
      }
    } else {
      console.error("videoRef 未挂载");
    }
  });
});
</script>
<style>
.video-content {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
</style>

效果:

到此这篇关于Vue使用EasyPlayerPro播放本地MP4视频的文章就介绍到这了,更多相关Vue EasyPlayerPro播放视频内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue修改对象的属性值后页面不重新渲染的实例

    vue修改对象的属性值后页面不重新渲染的实例

    今天小编就为大家分享一篇vue修改对象的属性值后页面不重新渲染的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • Vue纯前端如何实现导出简单Excel表格的功能

    Vue纯前端如何实现导出简单Excel表格的功能

    这篇文章主要介绍了如何在Vue项目中使用vue-json-excel插件实现Excel表格的导出功能,包括安装依赖、引入插件、使用组件、设置表头和数据、处理空数据情况、源代码修改以解决常见问题,需要的朋友可以参考下
    2025-01-01
  • Vue3 响应式高阶用法之customRef()的使用

    Vue3 响应式高阶用法之customRef()的使用

    customRef()是Vue3的高级工具,允许开发者创建具有复杂依赖跟踪和自定义更新逻辑的ref对象,本文详细介绍了customRef()的使用场景、基本用法、功能详解以及最佳实践,包括防抖、异步更新等用例,旨在帮助开发者更好地理解和使用这一强大功能
    2024-09-09
  • vue的.vue文件是怎么run起来的(vue-loader)

    vue的.vue文件是怎么run起来的(vue-loader)

    通过vue-loader,解析.vue文件,在webpack解析,拆解vue组件 ,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友参考下
    2018-12-12
  • Vue实现鼠标悬浮隐藏与显示图片效果@mouseenter和@mouseleave事件详解

    Vue实现鼠标悬浮隐藏与显示图片效果@mouseenter和@mouseleave事件详解

    在所做的Vue项目中,有时候需要在鼠标移动文字框的时候显示一些详细信息,下面这篇文章主要给大家介绍了关于Vue实现鼠标悬浮隐藏与显示图片效果@mouseenter和@mouseleave事件的相关资料,需要的朋友可以参考下
    2022-11-11
  • 正确更改Ant Design of Vue样式的问题

    正确更改Ant Design of Vue样式的问题

    这篇文章主要介绍了正确更改Ant Design of Vue样式的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-09-09
  • Vue.js父与子组件之间传参示例

    Vue.js父与子组件之间传参示例

    本篇文章主要介绍了Vue.js父与子组件之间传参示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-02-02
  • Django+Vue.js实现搜索功能

    Django+Vue.js实现搜索功能

    本文主要介绍了Django+Vue.js实现搜索功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-06-06
  • Vue3使用Signature Pad实现电子签名功能

    Vue3使用Signature Pad实现电子签名功能

    Vue3签名板是一种在Vue3应用中实现用户签名功能的组件,Vue3-signature-pad的实现旨在为开发者提供一个简单易用的工具,使用户能够在前端界面上进行签名操作,常见于电子商务、电子合同等场景,本文介绍了Vue3使用Signature Pad实现电子签名功能,需要的朋友可以参考下
    2025-04-04
  • vue项目接口域名动态获取操作

    vue项目接口域名动态获取操作

    这篇文章主要介绍了vue项目接口域名动态获取操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08

最新评论