vue

关于vueh5页面对接即构视频记录

2022-03-20  本文已影响0人  Morbid_D

1.需要直接引入js ZegoExpressWebRTC.js

2.代码可以直接使用。

<template>

  <div class="videoConsultation">

    <video  id="publishVideo" style="object-fit: fill;" width="150" height="200" ref="publishVideo"  autoplay playsinline

          class="onInfo"></video>

    <video  poster="../../static/images/1.png"  id="playVideo"  style="object-fit: fill;" width="100vw" height="100vh"  ref="playVideo" autoplay playsinline

          class="dotInfo"></video>

  <div @click="noceDot" class="loginRoomOption" v-if="playStreamStatus==false">

    <img src="../../static/images/phone.png" alt="" class="phoneIcon">

  </div>

    <div @click="logoutRoom" class="loginRoomOptions" v-else>

    <img src="../../static/images/phone.png" alt="" class="phoneIcon">

  </div>

  <div class="mask" v-if="guidetype">

      <img src="../../static/images/mask1.png" alt="" class="mask1">

      <img src="../../static/images/right.png" alt="" class="mask2">

      <div class="maskTip">在其他浏览器打开</div>

    </div>

  </div>

</template>

<script>

import {plus} from '../../static/js/numPrecisions'

import  '../assets/js/express_sdk/ZegoExpressWebRTC.js'

import {getOrderInfo,docLaunch} from  '@/https/api'

import wx from 'weixin-jsapi'

import CryptoJS from "crypto-js";//加密文件

import { Toast } from 'vant'

export default {

  name:"home",

  data(){

    return{

      appID:3151745,//

      server:'wss://webliveroom3151745-api.imzego.com/ws',

      userID:'',//用户id

      roomID: '',

      token:'',

      streamID: '',//推流id

      playStreamID: '',//拉流id

      zg: null,

      localStream: null,

      remoteStream: null,

      isLogin: false,

      videoCodec: localStorage.getItem('VideoCodec') === 'H.264' ? 'H264' : 'VP8',

      audioDeviceList:[],

      videoDeviceList:[],

      createSuccessSvgStatus:false,

      checkSystemRequireStatus:'',

      connectStatus:'DISCONNECTED',

      microphoneDevicesVal:null,

      cameraDevicesVal:'',

      cameraCheckStatus:true,

      microphoneCheckStatus:true,

      publishStreamStatus: false,

      videoCheckStatus:true,

      audioCheckStatus:true,

      playStreamStatus:false,

      publishInfoStreamID:'',

      playInfoStreamID:'',

      guidetype:false,

      isWeiXin:false,

      videoInfo:'',//传递的参数信息

      orderDetail:'',//订单信息

    }

  },

  mounted(){

  },

  created(){

    this.$nextTick(() => {

  //调整音量为0

        this.$refs.publishVideo.volume = 1;

        this.$refs.playVideo.volume = 1;

      })

    this.isWeiXin = navigator.userAgent.toLowerCase().indexOf('micromessenger') > -1 ? true : false

    console.log('2222' + this.isWeiXin)

    let u = navigator.userAgent

    if(this.isWeiXin){//微信环境

      if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){//判断是否为ios

        this.guidetype = true

      }else{

        this.getOrderInfo()

      }

    }else{

      this.getOrderInfo()

    }

  },

  destroyed(){

    this.logoutRoom()

  },

  methods:{

    getOrderInfo(){

      let data = {

        id:this.$route.query.id

      }

      getOrderInfo(data).then(res=>{

        console.log('订单信息的结果' + res)

        if(res.data.status==0){

          this.roomID = res.data.data.roomId.toString(),

          this.userID = res.data.data.customerId.toString(),//患者的id 需要加10000

          this.streamID = plus('1000000',res.data.data.customerId).toString()//包括推流的id

          this.playStreamID =plus('2000000',res.data.data.docId).toString()//引流的id需要加10000

          this.token = res.data.data.zgtoken

          this.orderDetail = res.data.data

          if(res.data.data.orderState==1){

            this.createZegoExpressEngineOption()

          }else if(res.data.data.orderState==2){

            this.createZegoExpressEngineOption()

          }else{

            //这里提示信息

            alert(res.data.data.orderStateDesc)

          }

        }

      }).catch(reg=>{

        console.log('reg' +reg)

      })

    },

    async enumDevices(){

        const deviceInfo = await this.zg.enumDevices();

        this.audioDeviceList = deviceInfo &&

            deviceInfo.microphones.map((item, index) => {

                if (!item.deviceName) {

                    item.deviceName = 'microphone' + index;

                }

                console.log('microphone: ' + item.deviceName);

                return item;

            });

            this.audioDeviceList.push({deviceID:0,deviceName: '禁止'});

            console.error('audioDeviceList' + JSON.stringify(this.audioDeviceList))

            this.microphoneDevicesVal = this.audioDeviceList[0].deviceID;

            this.changeAudioDevices()

        this.videoDeviceList = deviceInfo &&

            deviceInfo.cameras.map((item, index) => {

                if (!item.deviceName) {

                    item.deviceName = 'camera' + index;

                }

                console.log('camera: ' + item.deviceName);

                return item;

            });

        this.videoDeviceList.push({deviceID:0,deviceName: '禁止'});

        this.cameraDevicesVal = this.videoDeviceList[0].deviceID;

    },

    initEvent() {

        this.zg.on('roomStateUpdate', (roomId, state) => {//房间状态监听

            console.log('state '+ state)

            if (state === 'CONNECTED' && this.isLogin) {

                this.connectStatus = 'CONNECTED';

            }

            if (state === 'DISCONNECTED' && !this.isLogin) {

                this.connectStatus = 'DISCONNECTED';

            }

            if (state === 'DISCONNECTED' && this.isLogin) {

                location.reload()

            }

        })

        this.zg.on('roomStreamUpdate',(roomID,updateType,streamList)=>{

          console.log('list',streamList)

          console.log(updateType)

          if(updateType == 'ADD'){//进行啦六

            this.playStreamID = streamList[0].streamID

            this.startPlaying()

          }else if (updateType == 'DELETE') {

              // 流删除,停止拉流

              this.stopPlayingStream(this.playStreamID)

              this.logoutRoom()

          }else{

            // this.stopPlayingStream(this.playStreamID)

            // this.logoutRoom()

          }

        })

        this.zg.on('publisherStateUpdate', (result) => {

            if (result.state === 'PUBLISHING') {

                this.publishInfoStreamID = result.streamID;

            } else if (result.state === 'NO_PUBLISH') {

                this.publishInfoStreamID = "";

            }

        });

        this.zg.on('playerStateUpdate', (result) => {

            if (result.state === 'PLAYING') {

                this.playInfoStreamID = result.streamID;

            } else if (result.state === 'NO_PLAY') {

                this.playInfoStreamID = "";

            }

        });

    },

            // Step1 Create ZegoExpressEngine

            createZegoExpressEngine() {

                this.zg = new ZegoExpressEngine(this.appID, this.server);

                window.zg = this.zg;

                this.checkSystemRequirements()

                this.checkSystemRequire()//打开对应的权限

            },

            // Step2 Check system requirements

            async checkSystemRequirements() {

                console.log('sdk version is', this.zg.getVersion());

                try {

                    const result = await this.zg.checkSystemRequirements();

                    console.warn('checkSystemRequirements ', result);

                    if (!result.webRTC) {

                        console.error('browser is not support webrtc!!');

                        return false;

                    } else if (!result.videoCodec.H264 && !result.videoCodec.VP8) {

                        console.error('browser is not support H264 and VP8');

                        return false;

                    } else if (!result.camera && !result.microphones) {//打不开微信摄像头

                        console.error('camera and microphones not allowed to use');

                        return false;

                    } else if (result.videoCodec.VP8) {

                        if (!result.screenSharing) console.warn('browser is not support screenSharing');

                    } else {

                        console.log('不支持VP8,请前往混流转码测试');

                    }

                    return true;

                } catch (err) {

                    console.error('checkSystemRequirements', err);

                    return false;

                }

            },

            // Step3 Login room

            async loginRoom(roomId, userId, userName, token) {

                return await this.zg.loginRoom(roomId, token, {

                    userID: userId,

                    userName

                });

            },

            // Step4 Start Publishing Stream

            async startPublishingStream(streamId, config) {

              let  that = this

                try {

                    that.localStream = await this.zg.createStream(config);

                    console.log('localStream' +JSON.stringify(this.localStream))

                    that.zg.startPublishingStream(streamId, this.localStream, { videoCodec:this.videoCodec });

                    that.$refs['publishVideo'].srcObject = this.localStream;

                    return true;

                } catch (err) {

                    return false;

                }

            },

            // Step5 Start Play Stream

            async startPlayingStream(streamId, options = {}) {

                try {

                    this.remoteStream = await this.zg.startPlayingStream(streamId, options);

                    this.$refs['playVideo'].srcObject = this.remoteStream;

                    return true;

                } catch (err) {

                    return false;

                }

            },

            // Logout room

            logoutRoom(roomId){

                this.stopPublishingStream(this.streamID)

                this.zg.logoutRoom(this.roomId);

                this.clearStream()

                this.playStreamStatus = false

                this.$router.go(-1)

            },

            // Stop Publishing Stream

            async stopPublishingStream(streamId) {

                this.zg.stopPublishingStream(streamId);

            },

            // Stop Play Stream

            async stopPlayingStream(streamId){

                this.zg.stopPlayingStream(streamId);

            },

            clearStream(){

                this.localStream && this.zg.destroyStream(this.localStream);

                this.$refs['publishVideo'].srcObject = null;

                this.localStream = null;

                this.remoteStream && this.zg.destroyStream(this.remoteStream);

                this.$refs['playVideo'].srcObject = null;

                this.remoteStream = null;

            },

            changeAudioDevices(){

                if(!this.zg || !this.localStream){

                    return

                }

                const isMicrophoneMuted = this.zg.isMicrophoneMuted();

                if(!isNaN(this.microphoneDevicesVal) && !isMicrophoneMuted){

                    this.zg.muteMicrophone(true);

                }else{

                    this.zg.muteMicrophone(false);

                    this.zg.useAudioDevice(this.localStream, this.microphoneDevicesVal);

                }

            },

            // ==============================================================

            // This part of the code binds the button click event

            // ==============================================================

            createZegoExpressEngineOption(){

                if(!this.createSuccessSvgStatu) {

                    this.createZegoExpressEngine();

                    this.createSuccessSvgStatus = true;

                    this.initEvent();

                    this.loginRoomOption()

                }

            },

            noceDot(){

              let data ={

                  docId:this.orderDetail.docId,

                  spOrderId:this.orderDetail.id

              }

              docLaunch(data).then(res=>{

                if(res.data.status==0){

                  this.playStreamStatus = true

                }else{

                  Toast.error('通知失败')

                }

              })

            },

            async checkSystemRequire(){

              console.log('到这里了')

                if (!this.zg) return alert('you should create zegoExpressEngine');

                const result = await this.checkSystemRequirements();

                console.log('result' + result)

                if (result) {

                    this.checkSystemRequireStatus = 'SUCCESS';

                    this.enumDevices();

                } else {

                    this.checkSystemRequireStatus = 'ERROR';

                }

            },

            async loginRoomOption(){

                try {

                    this.checkSystemRequire()//打开对应的权限

                    this.isLogin =  await this.loginRoom(this.roomID, this.userID, '患者', this.token);//加入完成后进行推流

                    console.log('this.isLogin'+this.isLogin)

                    this.isLogin?this.startPublishing():''

                } catch (err) {

                    this.isLogin = false;

                    console.log(err);

                }

            },

            async startPublishing(){//推流

                const flag = await this.startPublishingStream(this.streamID, {

                    camera: {

                        audioInput: this.microphoneDevicesVal,

                        videoInput: this.cameraDevicesVal,

                        video: this.cameraCheckStatus,

                        audio: this.microphoneCheckStatus,

                    },

                })

                console.log('flag' + flag)

                if (flag) {

                    this.publishStreamStatus = true;

                }

            },

            async startPlaying(){

                const flag = await this.startPlayingStream(this.playStreamID, {

                    video: this.videoCheckStatus,

                    audio: this.audioCheckStatus

                });

                console.log('flags' +flag)

                if (flag) {

                  this.playStreamStatus  = true

                }

            },

  }

}

</script>

<style lang="less" scoped>

.videoConsultation{

  height: 100vh;

  position: relative;

  .mask{

    position: fixed;

    top: 0;

    right: 0;

    bottom: 0;

    left: 0;

    background: rgba(0,0,0,.6);

    z-index: 11;

    height: 100vh;

    animation: .9s bounceIn;

    .mask1{

      width: 80px;

      height: 41px;

      position: absolute;

      right: 30px;

      top: 40px;

    }

    .mask2{

      width: 263px;

      height: 214px;

      position: absolute;

      right: 130px;

      top: 60px;

    }

    .maskTip{

      height: 32px;

      font-size: 34px;

      font-family: Source Han Sans CN;

      font-weight: 400;

      color: #FFFFFF;

      position: absolute;

      right: 0;

      top: 300px;

      width: 100%;

      text-align: center;

    }

    .maskButton{

      position: absolute;

      right: 0;

      top: 400px;

      width: 100%;

      .maskButtons{

        text-align: center;

        width: 230px;

        height: 88px;

        background: #45BEFD;

        border-radius: 24px;

        font-size: 36px;

        font-family: Source Han Sans CN;

        font-weight: 400;

        color: #FFFFFF;

        line-height: 88px;

        margin: 0 auto;

      }

    }

  }

  .onInfo{

    position: absolute;

    right: 30px;

    z-index: 10;

    top: 120px;

  }

  .dotInfo{

    width: 100%;

    height: 100vh;

    position: absolute;

    left: 0;

    top: 0;

    right: 0;

    bottom: 0;

  }

  .loginRoomOption{

    position: absolute;

    bottom: 150px;

    left: 35%;

    width: 200px;

    height: 200px;

    background: green;

    border-radius: 50%;

    text-align: center;

    line-height: 200px;

    z-index: 10;

    .phoneIcon{

      width: 100px;

      height: 100px;

    }

  }

  .loginRoomOptions{

    position: absolute;

    bottom: 150px;

    left: 35%;

    width: 200px;

    height: 200px;

    background: red;

    border-radius: 50%;

    text-align: center;

    line-height: 200px;

    display: flex;

    align-items: center;

    justify-content: center;

    z-index: 10;

    .phoneIcon{

      width: 100px;

      height: 100px;

      display: flex;

      transform: rotate(134deg);

    }

  }

}

</style>

上一篇下一篇

猜你喜欢

热点阅读