0


前端实现视频流播放:封装一个可复用的HlsPlayer组件

简介

在前端开发中,播放视频流是一个常见的需求,尤其是在需要实时监控或直播的场景中。本文将分享如何封装一个基于

  1. hls.js

库的Vue组件,以便在任何需要的地方快速引用和播放视频流。

环境准备

首先,确保你的项目中已经安装了Vue框架和

  1. hls.js

库。如果没有安装

  1. hls.js

,可以通过npm进行安装:

npm install hls.js

组件封装

接下来,我们将创建一个名为

  1. HlsPlayer.vue

的Vue组件,用于播放HLS视频流。

  1. HlsPlayer.vue

的模板中,我们定义了一个

  1. video

元素,它将用于播放视频流。在脚本部分,我们首先导入

  1. Hls

类,然后定义组件的属性、数据、生命周期钩子和方法。在样式部分定义一些基本样式,确保视频播放器能够适应不同的屏幕尺寸。

  1. <template>
  2. <div class="myVideo">
  3. <video class="myVideo" ref="vedioEle" controls muted width="600"></video>
  4. <!-- <button @click="() => {this.video?.play()}">Play</button> -->
  5. </div>
  6. </template>
  7. <script>
  8. // 安装依赖: npm install hls.js
  9. import Hls from 'hls.js'
  10. export default {
  11. props:{
  12. url:{
  13. type: String,
  14. default:'',
  15. }
  16. },
  17. data() {
  18. return {
  19. hls:null, // hls实例
  20. video: null,
  21. timer:null
  22. }
  23. },
  24. created() {},
  25. watch: {
  26. url: {
  27. immediate: false,
  28. handler(newVal) {
  29. if (newVal) {
  30. this.initializePlayer();
  31. }
  32. }
  33. }
  34. },
  35. mounted() {
  36. this.$nextTick(() => {
  37. this.initializePlayer()
  38. })
  39. },
  40. beforeUnmount() {},
  41. methods: {
  42. initializePlayer() {
  43. this.video = this.$refs.vedioEle;
  44. if (!this.url) {
  45. // 如果url为空,显示加载提示
  46. this.showLoadingIndicator();
  47. return;
  48. }
  49. this.hlsPlay();
  50. },
  51. showLoadingIndicator() {
  52. // 显示加载提示的逻辑
  53. // 这里可以是修改DOM,或者显示一个加载动画等
  54. console.log('正在加载视频...');
  55. // 您可能需要添加一些逻辑来定时检查url是否已经赋值
  56. // 如果赋值了,就调用this.hlsPlay()来开始播放
  57. },
  58. hlsPlay() {
  59. this.video = this.$refs.vedioEle
  60. if (Hls.isSupported()) {
  61. //如果支持hLs.js (MediaSource Extensions)
  62. this.hls = new Hls()
  63. this.hls.loadSource(this.url)
  64. this.hls.attachMedia(this.video)
  65. this.hls.on(Hls.Events.BUFFERING, (event, data) => {
  66. console.log('缓冲中...');
  67. });
  68. this.hls.on(Hls.Events.MANIFEST_LOADED, (event, data) => {
  69. console.log('播放列表已更新,尝试恢复播放');
  70. if (!this.video.paused) {
  71. this.video.play();
  72. }
  73. });
  74. //自动播放
  75. this.hls.on(Hls.Events.MANIFEST_PARSED, (event, data) => {
  76. this.timer = setTimeout(() => {
  77. this.video.play()
  78. },500);
  79. })
  80. } else if (this.video.canPlayType('application/vnd.apple.mpegurl')) {
  81. //如果支持原生播放
  82. this.video.src = this.url
  83. //自动播放
  84. this.video.addEventListener('canplay', () => {
  85. this.timer = setTimeout(() => {
  86. this.video.play()
  87. },500);
  88. });
  89. }
  90. }
  91. },
  92. beforeDestroy() {
  93. if (this.hls) {
  94. this.hls.destroy();
  95. }
  96. clearTimeout(this.timer);
  97. }
  98. }
  99. </script>
  100. <style>
  101. .myVideo {
  102. width: 100%;
  103. height: 100%;
  104. }
  105. </style>

使用组件

一旦

  1. HlsPlayer.vue

组件被创建,你可以在任何Vue组件中通过以下方式使用它

  1. <div class="imgBox" >
  2. <HlsPlayer :url="state.hlsplayUrl" v-if="state.hlsplayUrl"></HlsPlayer>
  3. </div>
  4. import HlsPlayer from '@/views/securityPatrol/components/HlsPlay.vue';
  5. const state = reactive({
  6. // 使用网上可播放使用的地址
  7. hlsplayUrl:'https://cph-p2p-msl.akamaized.net/hls/live/2000341/test/master.m3u8'
  8. });

防抖优化

在前端开发中,实现视频流播放时,用户频繁点击按钮可能会导致服务器多次请求视频流地址,增加服务器负担并可能引起播放失败。为解决此问题,我们可以使用防抖技术优化按钮点击事件处理。防抖技术确保在指定时间间隔内,无论事件触发多少次,只有一次函数调用被执行。以下是实现步骤:

  1. 包装请求逻辑:使用debounce函数包装请求视频流的逻辑,设置1000毫秒的防抖时间。
  2. 实现防抖函数:创建debounce函数,通过setTimeoutclearTimeout控制函数执行时机。
  3. 处理点击事件:在点击事件处理函数中使用防抖函数,避免频繁请求。
  1. // 包装请求视频流的逻辑
  2. const debouncedRequestStream = debounce(() => {
  3. killProcess().then(res => {
  4. if (res.data.code == 200) {
  5. const cameraIp = 1; // 这里应该是动态获取的IP地址
  6. putStream({ cameraIp:cameraIp }).then(res => {
  7. state.hlsplayUrl = res.data;
  8. });
  9. }
  10. });
  11. }, 1000); // 1000毫秒防抖时间
  12. // 防抖函数
  13. function debounce(func, delay) {
  14. let timer = null;
  15. return function(...args) {
  16. clearTimeout(timer);
  17. timer = setTimeout(() => {
  18. func.apply(this, args);
  19. }, delay);
  20. };
  21. }
  22. // 点击事件
  23. const handleItemClick = (row, index, i) => {
  24. state.hlsplayUrl = ''
  25. // 使用防抖函数处理视频流请求
  26. debouncedRequestStream();
  27. };

效果展示

结语

通过封装

  1. HlsPlayer

组件,我们能够轻松地在项目中实现视频流的播放功能。这种封装方式不仅提高了代码的复用性,还使得维护变得更加简单。希望这篇文章能够帮助你在前端项目中实现视频流播放的需求。


本文转载自: https://blog.csdn.net/m0_54340021/article/details/140323234
版权归原作者 小金子J 所有, 如有侵权,请联系我们删除。

“前端实现视频流播放:封装一个可复用的HlsPlayer组件”的评论:

还没有评论