WEBRTC + vue 建立连接 本地测试

WEBRTC + vue 建立连接 本地测试

有socket网络远端交互版本的 可以评论联系我 我发出来

vue复制到文件中

<template>
  <div class="home">
    <div id="contentHolder" class="content-holder">
      <video id="videoA" width="550" height="450" autoplay ref="videoA"></video>

      <video id="videoB" width="550" height="450" autoplay ref="videoB"></video>
    </div>
    <button @click="initVido()">打开</button>
    <button @click="call()">呼叫</button>
  </div>
</template>

<script>
let pc1;
let pc2;
let localStream;
let startTime;
export default {
  name: "Home",
  data() {
    return {
      offerOptions: {
        offerToReceiveAudio: 1,
        offerToReceiveVideo: 1,
      },
    };
  },

  methods: {
    initVido() {
      let _this = this;
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        navigator.mediaDevices
          .getUserMedia({
            video: true,
            audio: true,
          })
          .then(function (stream) {
            var video = _this.$refs.videoA;
            video["srcObject"] = stream;
            localStream = stream;
            video.play();
            if (pc1) {
              localStream
                .getTracks()
                .forEach((track) => pc1.addTrack(track, localStream));

              console.log("Added local stream to pc1");
            }
          })
          .catch(function (err) {
            console.log(err);
          });
      }

      const remoteVideo = this.$refs.videoB;
      remoteVideo.addEventListener("resize", () => {
        console.log(
          `Remote video size changed to ${remoteVideo.videoWidth}x${
            remoteVideo.videoHeight
          } - Time since pageload ${performance.now().toFixed(0)}ms`
        );
        // We'll use the first onsize callback as an indication that video has started
        // playing out.
        if (startTime) {
          const elapsedTime = window.performance.now() - startTime;
          console.log("Setup time: " + elapsedTime.toFixed(3) + "ms");
          startTime = null;
        }
      });
    },

    async call() {
      const configuration = {};
      startTime = window.performance.now();

      pc1 = new RTCPeerConnection(configuration);
      pc2 = new RTCPeerConnection(configuration);
      // 添加 onIceCandidate 监听
      pc1.addEventListener("icecandidate", (e) => this.onIceCandidate1(pc1, e));
      pc2.addEventListener("icecandidate", (e) => this.onIceCandidate2(pc2, e));
      
      pc1.addEventListener("iceconnectionstatechange", (e) =>
        this.onIceStateChange(pc1, e)
      );
      pc2.addEventListener("iceconnectionstatechange", (e) =>
        this.onIceStateChange(pc2, e)
      );
      pc2.addEventListener("track", this.gotRemoteStream);

      if (localStream) {
        localStream.getTracks().forEach((track) => pc1.addTrack(track, localStream));
        console.log("Added local stream to pc1");
      }

      try {
        console.log("pc1 createOffer start");
        const offer = await pc1.createOffer(this.offerOptions);
        await this.onCreateOfferSuccess(offer);
      } catch (e) {
        this.onCreateSessionDescriptionError(e);
      }
    },

    async onIceCandidate1(pc1, event) {
      try {
        await pc2.addIceCandidate(event.candidate);
        this.onAddIceCandidateSuccess(pc1);
      } catch (e) {
        this.onAddIceCandidateError(pc1, e);
      }
    },

    async onIceCandidate2(pc2, event) {
      try {
        await pc1.addIceCandidate(event.candidate);
        this.onAddIceCandidateSuccess(pc2);
      } catch (e) {
        this.onAddIceCandidateError(pc2, e);
      }
    },

    onIceStateChange(pc) {
      if (pc) {
        if (pc) {
          console.log(
            `${this.getName(pc)} ICE state: ${pc.iceConnectionState}`
          );
          // console.log("ICE state change event: ", event);
        }
      }
    },

    async onCreateOfferSuccess(desc) {
      // console.log(`Offer from pc1\n${desc.sdp}`);
      console.log("pc1 setLocalDescription start");
      try {
        await pc1.setLocalDescription(desc);
        this.onSetLocalSuccess(pc1);
      } catch (e) {
        this.onSetSessionDescriptionError(e);
      }

      console.log("pc2 setRemoteDescription start");
      try {
        await pc2.setRemoteDescription(desc);
        this.onSetRemoteSuccess(pc2);
      } catch (e) {
        this.onSetSessionDescriptionError(e);
      }

      console.log("pc2 createAnswer start");
      try {
        const answer = await pc2.createAnswer();
        await this.onCreateAnswerSuccess(answer);
      } catch (e) {
        console.log("pc2创建本地应答失败");
        this.onCreateSessionDescriptionError(e);
      }
    },

    async onCreateAnswerSuccess(desc) {
      // console.log(`Answer from pc2:\n${desc.sdp}`);
      console.log("pc2 setLocalDescription start");
      try {
        await pc2.setLocalDescription(desc);
        this.onSetLocalSuccess(pc2);
      } catch (e) {
        this.onSetSessionDescriptionError(e);
      }
      console.log("pc1 setRemoteDescription start");
      try {
        await pc1.setRemoteDescription(desc);
        this.onSetRemoteSuccess(pc1);
      } catch (e) {
        this.onSetSessionDescriptionError(e);
      }
    },

    onAddIceCandidateSuccess(pc) {
      console.log(`${this.getName(pc)} addIceCandidate success`);
    },

    onAddIceCandidateError(pc, error) {
      console.log(
        `${this.getName(pc)} failed to add ICE Candidate: ${error.toString()}`
      );
    },

    onCreateSessionDescriptionError(error) {
      console.log(error);
      console.error(
        `Failed to create session description: ${error.toString()}`
      );
    },

    onSetLocalSuccess(pc) {
      console.log(`${this.getName(pc)} setLocalDescription complete`);
    },

    onSetRemoteSuccess(pc) {
      console.log(`${this.getName(pc)} setRemoteDescription complete`);
    },

    onSetSessionDescriptionError(error) {
      console.error(`设置 session description 错误: ${error.toString()}`);
    },

    getName(pc) {
      return pc === pc1 ? "pc1" : "pc2";
    },

    gotRemoteStream(e) {
      var remoteVideo = this.$refs.videoB;
      if (remoteVideo.srcObject !== e.streams[0]) {
        remoteVideo.srcObject = e.streams[0];
        console.log("pc2 received remote stream");
      }
    },
  },
};
</script>

<style scoped>
.content-holder {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
</style>


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值