[JavaScript] HTML5 播放hls流媒体视频流

WebVincent 2020-06-06

在最新版的 Android webview 中不用任何插件,可以直接播放

在windows10自带的Edge浏览器 可直接播放,PC端 safari浏览器 可直接播放

PC端chrome,IE,Firefox以及集成以上内核的各种浏览器,以及旧版的Android SDK的webview 不能播放

在不能播放的情况下,需要引入hls.js

如下示例:

<template>
  <div class="camera-module">
    <div class="video-view">
      <video ref="video" id="video-rtmp" preload="auto" autoplay="autoplay" muted></video>
    </div>
  </div>
</template>
<script>
  import {getCamera} from ‘../../api/proxyApi‘
  import Hls from ‘hls.js‘
  export default {
    name: ‘CameraModule‘,
    data () {
      return {
        url: ‘‘,
        hls: null
      }
    },
    mounted () {
      getCamera ({
        cameraIndexCode: ‘30615f71e6634fb692eec993aa6c539e‘,
        protocol: ‘hls‘
     }).then(resp => {
       const data = JSON.parse(resp)
       console.log(‘获取监控点视频流URL:‘, data)
       if (data.code === ‘0‘) {
         this.url = data.data.url
       this.$nextTick(() => {
         this.getStream(this.url)
       })
      }
     })
    },
    methods: {
      getStream (url) {
        if (Hls.isSupported()) {
          this.hls = new Hls();
          this.hls.loadSource(url);
          this.hls.attachMedia(this.$refs.video);

          this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
            console.log("加载成功");
            this.$refs.video.play();
          });
          this.hls.on(Hls.Events.ERROR, (event, data) => {
            // console.log(event, data);
            // 监听出错事件
            console.log("加载失败");
          });
        } else if (this.$refs.video.canPlayType(‘application/vnd.apple.mpegurl‘)) {
          // this.$refs.video.src = ‘https://video-dev.github.io/streams/x36xhzz/x36xhzz.m3u8‘;
          // this.$refs.video.addEventListener(‘loadedmetadata‘,function() {
          //   this.$refs.video.play();
          // });
        }
      },
      videoPause () {
        if (this.hls) {
          this.$refs.video.pause();
          this.hls.destroy();
          this.hls = null;
        }
      }
    }
  }
</script>

相关推荐