vue2-rtsp视频流播放

 <Videos :rtsp="item.rtspUrl"></Videos>
swiperList: [
        {
          id: 1,
          title: "",
          rtspUrl: 'rtsp://rtspstream:cb50b0754546ed4cbfe327e6d9f34d93@zephyr.rtsp.stream/movie',
        },
        {
          id: 2,
          title: "",
          rtspUrl: 'rtsp://rtspstream:cb50b0754546ed4cbfe327e6d9f34d93@zephyr.rtsp.stream/movie',
        },
        {
          id: 3,
          title: "",
          rtspUrl: 'rtsp://rtspstream:cb50b0754546ed4cbfe327e6d9f34d93@zephyr.rtsp.stream/movie',
        },
      ],
import Videos from "./webrtc/webrtcstreamer.vue";

 

<template>
  <div id="video-contianer">
    <video
      class="video"
      ref="video"
      preload="auto"
      autoplay="autoplay"
      width="100%"
      height="100%"
      muted="muted"
    />
    <!-- muted -->
    <div
      class="mask"
      @click="handleClickVideo"
      :class="{ 'active-video-border': selectStatus }"
    ></div>
  </div>
</template>

<script>
import WebRtcStreamer from "./webrtcstreamer11.js";

export default {
  name: "videoCom",
  props: {
    rtsp: {
      type: String,
      required: true,
    },
    isOn: {
      type: Boolean,
      default: false,
    },
    spareId: {
      type: Number,
    },
    selectStatus: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      socket: null,
      result: null, // 返回值
      pic: null,
      webRtcServer: null,
      clickCount: 0, // 用来计数点击次数
      //rtsp:'rtsp://rtspstream:cb50b0754546ed4cbfe327e6d9f34d93@zephyr.rtsp.stream/movie'
    };
  },
  watch: {
    rtsp() {
      // do something
      console.log(this.rtsp);
      this.webRtcServer.disconnect();
      //this.initVideo();
    },
  },
  destroyed() {
    this.webRtcServer.disconnect();
  },
  beforeCreate() {
    window.onbeforeunload = () => {
      this.webRtcServer.disconnect();
    };
  },
  created() {
    this.$nextTick(() => {
      this.init();
    });
  },
  mounted() {
    this.initVideo();
  },
  methods: {
    initVideo() {
      try {
        //连接后端的IP地址和端口
        this.webRtcServer = new WebRtcStreamer(
          this.$refs.video,
          `http://127.0.0.1:8000`
          //  `http://192.168.18.104:8080`
        );
        //向后端发送rtsp地址
        this.webRtcServer.connect(this.rtsp);
      } catch (error) {
        console.log(error);
      }
    },
    init() {
      var video = document.querySelector("video");
      video.addEventListener("click", function () {
        video.muted = true;
        video.autoplay = true;
      });
    },
    /* 处理双击 单机 */
    dbClick() {
      this.clickCount++;
      if (this.clickCount === 2) {
        this.btnFull(); // 双击全屏
        this.clickCount = 0;
      }
      setTimeout(() => {
        if (this.clickCount === 1) {
          this.clickCount = 0;
        }
      }, 250);
    },
    /* 视频全屏 */
    btnFull() {
      const elVideo = this.$refs.video;
      if (elVideo.webkitRequestFullScreen) {
        elVideo.webkitRequestFullScreen();
      } else if (elVideo.mozRequestFullScreen) {
        elVideo.mozRequestFullScreen();
      } else if (elVideo.requestFullscreen) {
        elVideo.requestFullscreen();
      }
    },
    /* 
      ison用来判断是否需要更换视频流
      dbclick函数用来双击放大全屏方法
      */
    handleClickVideo() {
      if (this.isOn) {
        this.$emit("selectVideo", this.spareId);
        this.dbClick();
      } else {
        this.btnFull();
      }
    },
  },
};
</script>

<style scoped lang="scss">
.active-video-border {
  border: 2px salmon solid;
}
#video-contianer {
  position: relative;
  // width: 100%;
  // height: 100%;
  .video {
    // width: 100%;
    // height: 100%;
    // object-fit: cover;
  }
  .mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
}
</style>

 

var WebRtcStreamer = (function() {

    /** 
     * Interface with WebRTC-streamer API
     * @constructor
     * @param {string} videoElement - id of the video element tag
     * @param {string} srvurl -  url of webrtc-streamer (default is current location)
    */
    var WebRtcStreamer = function WebRtcStreamer (videoElement, srvurl) {
        if (typeof videoElement === "string") {
            this.videoElement = document.getElementById(videoElement);
        } else {
            this.videoElement = videoElement;
        }
        this.srvurl           = srvurl || location.protocol+"//"+window.location.hostname+":"+window.location.port;
        this.pc               = null;    
    
        this.mediaConstraints = { offerToReceiveAudio: true, offerToReceiveVideo: true };
    
        this.iceServers = null;
        this.earlyCandidates = [];
    }
    
    WebRtcStreamer.prototype._handleHttpErrors = function (response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response;
    }
    
    /** 
     * Connect a WebRTC Stream to videoElement 
     * @param {string} videourl - id of WebRTC video stream
     * @param {string} audiourl - id of WebRTC audio stream
     * @param {string} options -  options of WebRTC call
     * @param {string} stream  -  local stream to send
    */
    WebRtcStreamer.prototype.connect = function(videourl, audiourl, options, localstream) {
        this.disconnect();
        
        // getIceServers is not already received
        if (!this.iceServers) {
            console.log("Get IceServers");
            
            fetch(this.srvurl + "/api/getIceServers")
                .then(this._handleHttpErrors)
                .then( (response) => (response.json()) )
                .then( (response) =>  this.onReceiveGetIceServers(response, videourl, audiourl, options, localstream))
                .catch( (error) => this.onError("getIceServers " + error ))
                    
        } else {
            this.onReceiveGetIceServers(this.iceServers, videourl, audiourl, options, localstream);
        }
    }
    
    /** 
     * Disconnect a WebRTC Stream and clear videoElement source
    */
    WebRtcStreamer.prototype.disconnect = function() {		
        if (this.videoElement?.srcObject) {
            this.videoElement.srcObject.getTracks().forEach(track => {
                track.stop()
                this.videoElement.srcObject.removeTrack(track);
            });
        }
        if (this.pc) {
            fetch(this.srvurl + "/api/hangup?peerid=" + this.pc.peerid)
                .then(this._handleHttpErrors)
                .catch( (error) => this.onError("hangup " + error ))
    
            
            try {
                this.pc.close();
            }
            catch (e) {
                console.log ("Failure close peer connection:" + e);
            }
            this.pc = null;
        }
    }    
    
    /*
    * GetIceServers callback
    */
    WebRtcStreamer.prototype.onReceiveGetIceServers = function(iceServers, videourl, audiourl, options, stream) {
        this.iceServers       = iceServers;
        this.pcConfig         = iceServers || {"iceServers": [] };
        try {            
            this.createPeerConnection();
    
            var callurl = this.srvurl + "/api/call?peerid=" + this.pc.peerid + "&url=" + encodeURIComponent(videourl);
            if (audiourl) {
                callurl += "&audiourl="+encodeURIComponent(audiourl);
            }
            if (options) {
                callurl += "&options="+encodeURIComponent(options);
            }
            
            if (stream) {
                this.pc.addStream(stream);
            }
    
                    // clear early candidates
            this.earlyCandidates.length = 0;
            
            // create Offer
            this.pc.createOffer(this.mediaConstraints).then((sessionDescription) => {
                console.log("Create offer:" + JSON.stringify(sessionDescription));
                
                this.pc.setLocalDescription(sessionDescription)
                    .then(() => {
                        fetch(callurl, { method: "POST", body: JSON.stringify(sessionDescription) })
                            .then(this._handleHttpErrors)
                            .then( (response) => (response.json()) )
                            .catch( (error) => this.onError("call " + error ))
                            .then( (response) =>  this.onReceiveCall(response) )
                            .catch( (error) => this.onError("call " + error ))
                    
                    }, (error) => {
                        console.log ("setLocalDescription error:" + JSON.stringify(error)); 
                    });
                
            }, (error) => { 
                alert("Create offer error:" + JSON.stringify(error));
            });
    
        } catch (e) {
            this.disconnect();
            alert("connect error: " + e);
        }	    
    }
    
    
    WebRtcStreamer.prototype.getIceCandidate = function() {
        fetch(this.srvurl + "/api/getIceCandidate?peerid=" + this.pc.peerid)
            .then(this._handleHttpErrors)
            .then( (response) => (response.json()) )
            .then( (response) =>  this.onReceiveCandidate(response))
            .catch( (error) => this.onError("getIceCandidate " + error ))
    }
                        
    /*
    * create RTCPeerConnection 
    */
    WebRtcStreamer.prototype.createPeerConnection = function() {
        console.log("createPeerConnection  config: " + JSON.stringify(this.pcConfig));
        this.pc = new RTCPeerConnection(this.pcConfig);
        var pc = this.pc;
        pc.peerid = Math.random();		
        
        pc.onicecandidate = (evt) => this.onIceCandidate(evt);
        pc.onaddstream    = (evt) => this.onAddStream(evt);
        pc.oniceconnectionstatechange = (evt) => {  
            console.log("oniceconnectionstatechange  state: " + pc.iceConnectionState);
            if (this.videoElement) {
                if (pc.iceConnectionState === "connected") {
                    this.videoElement.style.opacity = "1.0";
                }			
                else if (pc.iceConnectionState === "disconnected") {
                    this.videoElement.style.opacity = "0.25";
                }			
                else if ( (pc.iceConnectionState === "failed") || (pc.iceConnectionState === "closed") )  {
                    this.videoElement.style.opacity = "0.5";
                } else if (pc.iceConnectionState === "new") {
                    this.getIceCandidate();
                }
            }
        }
        pc.ondatachannel = function(evt) {  
            console.log("remote datachannel created:"+JSON.stringify(evt));
            
            evt.channel.onopen = function () {
                console.log("remote datachannel open");
                this.send("remote channel openned");
            }
            evt.channel.onmessage = function (event) {
                console.log("remote datachannel recv:"+JSON.stringify(event.data));
            }
        }
        pc.onicegatheringstatechange = function() {
            if (pc.iceGatheringState === "complete") {
                const recvs = pc.getReceivers();
            
                recvs.forEach((recv) => {
                  if (recv.track && recv.track.kind === "video") {
                    console.log("codecs:" + JSON.stringify(recv.getParameters().codecs))
                  }
                });
              }
        }
    
        try {
            var dataChannel = pc.createDataChannel("ClientDataChannel");
            dataChannel.onopen = function() {
                console.log("local datachannel open");
                this.send("local channel openned");
            }
            dataChannel.onmessage = function(evt) {
                console.log("local datachannel recv:"+JSON.stringify(evt.data));
            }
        } catch (e) {
            console.log("Cannor create datachannel error: " + e);
        }	
        
        console.log("Created RTCPeerConnnection with config: " + JSON.stringify(this.pcConfig) );
        return pc;
    }
    
    
    /*
    * RTCPeerConnection IceCandidate callback
    */
    WebRtcStreamer.prototype.onIceCandidate = function (event) {
        if (event.candidate) {
            if (this.pc.currentRemoteDescription)  {
                this.addIceCandidate(this.pc.peerid, event.candidate);					
            } else {
                this.earlyCandidates.push(event.candidate);
            }
        } 
        else {
            console.log("End of candidates.");
        }
    }
    
    
    WebRtcStreamer.prototype.addIceCandidate = function(peerid, candidate) {
        fetch(this.srvurl + "/api/addIceCandidate?peerid="+peerid, { method: "POST", body: JSON.stringify(candidate) })
            .then(this._handleHttpErrors)
            .then( (response) => (response.json()) )
            .then( (response) =>  {console.log("addIceCandidate ok:" + response)})
            .catch( (error) => this.onError("addIceCandidate " + error ))
    }
                    
    /*
    * RTCPeerConnection AddTrack callback
    */
    WebRtcStreamer.prototype.onAddStream = function(event) {
        console.log("Remote track added:" +  JSON.stringify(event));
        
        this.videoElement.srcObject = event.stream;
        var promise = this.videoElement.play();
        if (promise !== undefined) {
          promise.catch((error) => {
            console.warn("error:"+error);
            this.videoElement.setAttribute("controls", true);
          });
        }
    }
            
    /*
    * AJAX /call callback
    */
    WebRtcStreamer.prototype.onReceiveCall = function(dataJson) {
    
        console.log("offer: " + JSON.stringify(dataJson));
        var descr = new RTCSessionDescription(dataJson);
        this.pc.setRemoteDescription(descr).then(() =>  { 
                console.log ("setRemoteDescription ok");
                while (this.earlyCandidates.length) {
                    var candidate = this.earlyCandidates.shift();
                    this.addIceCandidate(this.pc.peerid, candidate);				
                }
            
                this.getIceCandidate()
            }
            , (error) => { 
                console.log ("setRemoteDescription error:" + JSON.stringify(error)); 
            });
    }	
    
    /*
    * AJAX /getIceCandidate callback
    */
    WebRtcStreamer.prototype.onReceiveCandidate = function(dataJson) {
        console.log("candidate: " + JSON.stringify(dataJson));
        if (dataJson) {
            for (var i=0; i<dataJson.length; i++) {
                var candidate = new RTCIceCandidate(dataJson[i]);
                
                console.log("Adding ICE candidate :" + JSON.stringify(candidate) );
                this.pc.addIceCandidate(candidate).then( () =>      { console.log ("addIceCandidate OK"); }
                    , (error) => { console.log ("addIceCandidate error:" + JSON.stringify(error)); } );
            }
            this.pc.addIceCandidate();
        }
    }
    
    
    /*
    * AJAX callback for Error
    */
    WebRtcStreamer.prototype.onError = function(status) {
        console.log("onError:" + status);
    }
    
    return WebRtcStreamer;
    })();
    
    if (typeof window !== 'undefined' && typeof window.document !== 'undefined') {
        window.WebRtcStreamer = WebRtcStreamer;
    }
    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = WebRtcStreamer;
    }
    

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对不起,`vue-video-player`插件并不支持直接播放RTSP视频流。这个插件主要用于播放常见的视频格式,如MP4、WebM和HLS等。如果你需要在Vue播放RTSP视频流,你可能需要使用其他的解决方案。 一种可能的解决方案是使用`hls.js`库来转换RTSP流为HLS流,然后再使用`vue-video-player`插件来播放HLS流。下面是一个简单的示例: 首先,安装所需的依赖: ``` npm install video.js vue-video-player hls.js ``` 然后,在你的Vue组件中使用这些库: ```vue <template> <div> <video-player ref="videoPlayer" :options="playerOptions" @ready="onPlayerReady"></video-player> </div> </template> <script> import 'video.js/dist/video-js.css' import 'vue-video-player/src/custom-theme.css' import VideoPlayer from 'vue-video-player' import Hls from 'hls.js' export default { components: { VideoPlayer }, data() { return { playerOptions: { autoplay: true, controls: true, sources: [{ type: 'application/x-mpegURL', src: 'YOUR_HLS_URL' }] } } }, mounted() { if (Hls.isSupported()) { const video = this.$refs.videoPlayer.$refs.video const hls = new Hls() hls.loadSource('YOUR_RTSP_TO_HLS_URL') hls.attachMedia(video) } }, methods: { onPlayerReady(player) { // player is ready } } } </script> ``` 在上述示例中,你需要将`YOUR_RTSP_TO_HLS_URL`替换为将RTSP流转换为HLS流的实际URL。你可以使用工具如`ffmpeg`来完成这个转换过程。 请注意,RTSP流的转换和播放可能涉及到服务器端的配置和处理。这只是一个简单的示例,你可能需要根据你的实际需求做一些调整和改进。 希望这个解决方案对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值