首页 前端知识 Vue中使用JsSIP进行音视频通话

Vue中使用JsSIP进行音视频通话

2024-06-19 08:06:47 前端知识 前端哥 637 868 我要收藏

JsSIP官网地址:https://jssip.net/download/

  1. 下载JsSIP插件:npm install jssip;
  2. 在项目中引入:import JsSIP from “jssip”;
  3. 初始化SIP
let currentSession;
let userAgent;
let peer;
var msg_log = null;
sip_init () {
      let _this = this;
      msg_log = {
      	el: document.querySelector(".message"),
	   	log(msg) {
       		console.log("msg", msg);
       		this.titleText = msg;
       		this.el.innerHTML += `<span class="success">${new Date().toLocaleTimeString()}:${msg}</span>`;
      	},
       	error(msg) {
        	console.log("error", msg);
      	 	this.titleText = msg;
        	this.el.innerHTML += `<span class="error">${new Date().toLocaleTimeString()}:${msg}</span>`}
      }
        const selfVideo = document.querySelector("#selfVideo");
        // 本地加载完成 对端加载完成
        const socket = new JsSIP.WebSocketInterface(`wss://192.168.XX.XXX:16376`);
        const configuration = {
          sockets: [socket],
          uri: `sip:loginPhone@192.168.XX.XXX:16376;transport=wss`, // loginPhone为11位以1开头的数字
          password: "XXXXXX", // 密码
          register: true, // 自动注册
          session_timers: false,
        };
        var ua = new JsSIP.UA(configuration);
        ua.on("connected", () => {
          // msg_log.log("连线中")
          console.log("连线中");
        });
        ua.on("connecting", () => {
          // msg_log.log("接线中")
          console.log("接线中")
        });
        ua.on("disconnected", () => {
          // msg_log.error("取消连线")
          console.error("取消连线")
        });
        ua.on("registered", () =>{
          // msg_log.log(`--${name === "offer" ? 2001 : 2002}注册成功`);
        });
        ua.on("registrationExpiring", () => {
          // msg_log.log("注册即将到期,重新注册")
          console.log("注册即将到期,重新注册")
        });
        ua.on("registrationFailed", () => {
          // msg_log.error("注册失败")
          console.error("注册失败")
        });
        ua.on("unregistered", () => {
          // msg_log.log("取消注册")
          console.log("取消注册")
        });
        ua.on("sipEvent", () => {
          // msg_log.log("sipEvent")
          console.log("sipEvent")
        });
        ua.on("newRTCSession", function (data) {
          const { session, request, originator } = data;
          if (originator === "remote") {
            // msg_log.log("对方打电话过来了~~~");
          } else {
            // msg_log.log("拨打电话中~~~");
          }
          currentSession = session;
          // 连接中
          session.on("connecting", () => {
            // msg_log.log("通话连线时候触发")
          });
          // 连接已接受
          session.on("accepted", () => {
            _this.videoSpinner = true;
            // msg_log.log("通话接受时候触发")
          });
          session.on("sdp", () => {
            // msg_log.log("交换sdp信令事件触发")
          });
          session.on("failed", () => {
            // window.open("https://192.168.30.236:16376","验证")
            console.log("通话失败事件触发")
          });
          session.on("reinvite", () => {
            // msg_log.log("重新协商事件触发");
            audioElement.srcObject = null;
            // 自己的视频流
            // if (session._connection.getLocalStreams().length > 0) {
            //   selfVideo.srcObject = session?._connection.getLocalStreams()[0];
            //   selfVideo.play();
            // }
            // 接入的视频流
            // if (session?._connection.getRemoteStreams().length > 0) {
            //   remoteVideo.srcObject = session?._connection.getRemoteStreams()[0];
            //   remoteVideo.play();
            // }
          });
          session.on("progress", () => {
            if (originator === "remote") {
              // msg_log.log("电话过来拉~~~~~~~~~··");
              session.answer({
                mediaConstraints: { audio: true, video: _this.callType === 'video' ?true:false },
                // mediaStream: localStream,
              });
              // msg_log.log("我接听了");
            }
            // msg_log.log("接听事件在progress中触发");
          });
          session.on("confirmed", () => {
            // msg_log.log("呼叫确认--设置媒体流到音视频中");

            // 播放视频
            if (_this.callType === "video") {
              const remoteVideo = document.querySelector("#remoteVideo");
              console.log(remoteVideo,"remoteVideoremoteVideo");
              selfVideo.srcObject = null;
              remoteVideo.srcObject = null;

              // 自己的视频流
              // if (session._connection.getLocalStreams().length > 0) {
              //   // 接听后,判断localStream
              //   selfVideo.srcObject = session?._connection.getLocalStreams()[0];
              //   selfVideo.play();
              // }
              // 接入的视频流
              if (session?._connection.getRemoteStreams().length > 0) {
                remoteVideo.srcObject = session?._connection.getRemoteStreams()[0];
                remoteVideo.play();
              }
            }else if (_this.callType === "audio") {
              // 语音播放
              const stream = new MediaStream();
              const receivers = currentSession.connection?.getReceivers();
              if (receivers)
                receivers.forEach((receiver) => stream.addTrack(receiver.track));
                audioElement.srcObject = stream;
                // 最后都要播放
                audioElement.oncanplay = () => {
                  audioElement.play();
                };

            }
          });
          session.on("peerconnection", (data) => {
            // msg_log.log("对等连接事件触发");
          });
          session.on("connecting", (data) => {
            peer = session._connection;
            // msg_log.log("对等连接建立,connecting");
          });
          session.on("ended", () => {
            // msg_log.log("通话结束")
          });
        });
        userAgent = ua;
        ua.start();
    },```
 4. 拨打电话
```typescript
call() {
      let _this = this;
      const eventHandlers = {
        progress: function (e) {
          console.log("call is in progress");
        },
        failed: function (e) {
          _this.titleText = "对方已挂断!";
          _this.$message.error("无人应答!")
          _this.VoiceVisible = false;
          _this.ViewsVisible = false;
          console.log("call failed: ", e);
        },
        ended: function (e) {
          _this.$message.error("通话结束")
          console.log("call ended : ", e);
        },
        confirmed: function (e) {
          console.log("call confirmed");
        },
      }
      const opt = {
        mediaConstraints: {
          audio: true,
          video: _this.callType === 'video' ?true:false
        },
        eventHandlers,
      };
      // callPhone 要拨打的电话号码
      userAgent.call(`sip:${this.callPhone}@192.168.XX.XXX:16371`, opt);
    },
  1. 挂断电话
    userAgent.stop();// websocket会断开要重新注册
    userAgent.terminateSessions() // websocket不会断开
转载请注明出处或者链接地址:https://www.qianduange.cn//article/12785.html
标签
评论
发布的文章

期末总结

2024-06-29 19:06:42

爱心

2024-06-27 17:06:24

表白代码

2024-06-27 16:06:42

html5 css3 前端基础认识。

2024-06-26 23:06:18

CFT Show 信息收集篇

2024-06-26 23:06:28

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!