首页 > 其他分享 >JsSIP+FreeSwitch+Vue实现WebRtc音视频通话

JsSIP+FreeSwitch+Vue实现WebRtc音视频通话

时间:2024-06-13 11:00:59浏览次数:20  
标签:Vue console log remotedata JsSIP 音视频 userAgent null audio

效果

让同事帮我测的,在两个电脑分别打开该页面,一个注册 1007 分机号,另一个注册 1005,然后拨打视频电话
在这里插入图片描述
在这里插入图片描述

依赖版本

  • jssip:3.6.1

  • freeswitch:1.10.5-release~64bit

  • vue:2.6.12

488错误解决

freeswitch 配置文件 sip_profiles/internal.xml 中添加:

<param name="apply-candidate-acl" value="rfc1918.auto"/>
<param name="apply-candidate-acl" value="wan.auto"/>

前端完整代码

<template>
  <div class="test-sip">
    <el-switch
      v-model="logFlag"
      active-text="打开日志"
      inactive-text="关闭日志"
    >
    </el-switch>
    <div class="step">
      <h2>步骤 1:输入自己的分机号(1001-1019)</h2>
      <div class="step-box">
        <el-input
          v-model="userExtension"
          placeholder="请输入自己的分机号(1001-1010)"
          class="input-box"
          :disabled="localStream !== null"
        ></el-input>
        <el-button
          type="primary"
          @click="registerUser"
          class="step-button"
          :disabled="!userExtension || isRegisted"
        >
          注册
        </el-button>
      </div>
    </div>

    <div class="step">
      <h2>步骤 2:输入要呼叫的分机号(1001-1019)</h2>
      <div class="step-box">
        <el-input
          v-model="targetExtension"
          placeholder="请输入要呼叫的分机号(1001-1010)"
          class="input-box"
          :disabled="!isRegisted"
        ></el-input>
        <el-button
          type="primary"
          @click="startCall(false)"
          class="step-button"
          :disabled="!targetExtension || currentSession !== null"
        >
          拨打语音电话
        </el-button>
        <el-button
          type="primary"
          @click="startCall(true)"
          class="step-button"
          :disabled="!targetExtension || currentSession !== null"
        >
          拨打视频电话
        </el-button>
      </div>
    </div>

    <div class="step">
      <h2>其他操作</h2>
      <div class="step-box">
        <el-button
          type="primary"
          @click="hangUpCall"
          class="step-button"
          :disabled="currentSession == null"
        >
          挂断
        </el-button>
        <el-button
          type="primary"
          @click="unregisterUser"
          class="step-button"
          :disabled="!isRegisted"
        >
          取消注册
        </el-button>
        <el-button
          v-if="!localStream"
          type="primary"
          class="step-button"
          @click="captureLocalMedia"
          :disabled="currentSession !== null"
        >
          测试本地设备
        </el-button>
        <el-button
          v-else
          type="primary"
          class="step-button"
          @click="stopLocalMedia"
          :disabled="currentSession"
        >
          停止测试本地设备
        </el-button>
      </div>
    </div>

    <div class="step">
      <h2>音频:</h2>
      <div class="step-box">
        <audio id="audio" autoplay></audio>
      </div>
    </div>

    <div class="step">
      <h2>视频:</h2>
      <div class="step-box">
        <video id="meVideo" playsinline autoplay></video>
        <video id="remoteVideo" playsinline autoplay></video>
      </div>
    </div>
  </div>
</template>

<script>
import JsSIP from "jssip";

export default {
  name: "TestSip",
  data() {
    return {
      logFlag: false, // 是否打开日志
      userExtension: "", // 当前用户分机号
      targetExtension: "", // 目标用户分机号
      userAgent: null, // 用户代理实例
      password: "xxxx", // 密码
      serverIp: "xxxx.xxxx.x", // 服务器ip
      isRegisted: false, // 是否已注册
      localStream: null, // 本地流
      incomingSession: null, // 呼入的会话
      outgoingSession: null, // 呼出的会话
      currentSession: null, // 当前会话
      myHangup: false, // 是否我方挂断

      audio: null, // 音频
      meVideo: null, // 我方视频
      remoteVideo: null, // 对方视频
      constraints: {
        audio: true,
        video: {
          width: { max: 1280 },
          height: { max: 720 },
        },
      },
    };
  },
  computed: {
    ws_url() {
      return `ws://${this.serverIp}:5066`;
    },
  },
  watch: {
    logFlag: {
      handler(nV, oV) {
        nV ? JsSIP.debug.enable("JsSIP:*") : JsSIP.debug.disable("JsSIP:*");
      },
      immediate: true,
    },
  },
  mounted() {
    this.audio = document.getElementById("audio");
    this.meVideo = document.getElementById("meVideo");
    this.remoteVideo = document.getElementById("remoteVideo");
  },
  methods: {
    // 获取本地媒体设备
    captureLocalMedia() {
      console.log("获取到本地音频/视频");
      navigator.mediaDevices
        .getUserMedia(this.constraints)
        .then((stream) => {
          console.log("获取到本地媒体流");
          this.localStream = stream;

          // 连接本地麦克风
          if ("srcObject" in this.audio) {
            this.audio.srcObject = stream;
          } else {
            this.audio.src = window.URL.createObjectURL(stream);
          }
          // 如果有视频流,则连接本地摄像头
          if (stream.getVideoTracks().length > 0) {
            if ("srcObject" in this.meVideo) {
              this.meVideo.srcObject = stream;
            } else {
              this.meVideo.src = window.URL.createObjectURL(stream);
            }
          }
        })
        .catch((e) => {
          this.$modal.msgError("获取用户媒体设备错误: " + e.name);
        });
    },
    // 停止本地媒体设备
    stopLocalMedia() {
      if (this.localStream) {
        this.localStream.getTracks().forEach((track) => track.stop());
        this.localStream = null;
        // 清空音频和视频的 srcObject
        this.clearMedia("audio");
        this.clearMedia("meVideo");
      }
    },
    // 验证分机号,因为 freeswitch 默认会创建这些分机号
    isValidExtension(extension) {
      const extNumber = parseInt(extension, 10);
      return extNumber >= 1001 && extNumber <= 1019;
    },
    // 注册
    registerUser() {
      if (!this.isValidExtension(this.userExtension)) {
        this.$modal.msgError("分机号无效,请输入1001-1019之间的分机号");
        return;
      }

      const configuration = {
        sockets: [new JsSIP.WebSocketInterface(this.ws_url)],
        uri: `sip:${this.userExtension}@${this.serverIp};transport=ws`,
        password: this.password,
        contact_uri: `sip:${this.userExtension}@${this.serverIp};transport=ws`,
        display_name: this.userExtension,
        register: true, //指示启动时JsSIP用户代理是否应自动注册
        session_timers: false, //关闭会话计时器(根据RFC 4028)
      };
      this.userAgent = new JsSIP.UA(configuration);

      this.userAgent.on("connecting", () => console.log("WebSocket 连接中"));
      this.userAgent.on("connected", () => console.log("WebSocket 连接成功"));
      this.userAgent.on("disconnected", () =>
        console.log("WebSocket 断开连接")
      );
      this.userAgent.on("registered", () => {
        this.isRegisted = true;
        console.log("用户代理注册成功");
      });
      this.userAgent.on("unregistered", () => {
        this.isRegisted = false;
        console.log("用户代理取消注册");
      });
      this.userAgent.on("registrationFailed", (e) => {
        this.$modal.msgError(`用户代理注册失败: ${e.cause}`);
      });
      // this.userAgent.on("registrationExpiring", (e) => {
      //   /*
      //     在注册到期前几秒钟触发。拦截默认重新注册事件。

      //   */
      //   console.warn("registrationExpiring");
      // });
      this.userAgent.on("newRTCSession", (e) => {
        console.log("新会话: ", e);
        if (e.originator == "remote") {
          console.log("接听到来电");
          this.incomingSession = e.session;
          this.sipEventBind(e);
        } else {
          console.log("打电话");
          this.outgoingSession = e.session;

          this.outgoingSession.on("connecting", (data) => {
            console.info("onConnecting - ", data.request);
            this.currentSession = this.outgoingSession;
            this.outgoingSession = null;
          });

          this.outgoingSession.connection.addEventListener("track", (event) => {
            console.log("接收到远端track:", event.track);
            this.trackHandle(event.track, event.streams[0]);
          });
        }
      });
      this.userAgent.start();
      console.log("用户代理启动");
    },
    sipEventBind(remotedata, callbacks) {
      //接受呼叫时激发
      remotedata.session.on("accepted", () => {
        console.log("onAccepted - ", remotedata);
        if (remotedata.originator == "remote" && this.currentSession == null) {
          this.currentSession = this.incomingSession;
          this.incomingSession = null;
          console.log("setCurrentSession:", this.currentSession);
        }
      });

      remotedata.session.on("sdp", (data) => {
        console.log("onSDP, type - ", data.type, " sdp - ", data.sdp);
      });

      remotedata.session.on("progress", () => {
        console.log(remotedata);
        console.log("onProgress - ", remotedata.originator);
        if (remotedata.originator == "remote") {
          console.log("onProgress, response - ", remotedata.response);

          const isVideoCall = remotedata.request.body.includes("m=video");
          this.$modal
            .confirm(
              `检测到${remotedata.request.from.display_name}的${
                isVideoCall ? "视频" : "语音"
              }来电,是否接听?`
            )
            .then(() => {
              //如果同一电脑两个浏览器测试则video改为false,这样被呼叫端可以看到视频,两台电脑测试让双方都看到改为true
              remotedata.session.answer({
                mediaConstraints: { audio: true, video: isVideoCall },
              });
            })
            .catch(() => {
              this.hangUpCall();
              return;
            });
        }
      });

      remotedata.session.on("peerconnection", () => {
        console.log("onPeerconnection - ", remotedata.peerconnection);

        if (remotedata.originator == "remote" && this.currentSession == null) {
          remotedata.session.connection.addEventListener("track", (event) => {
            console.info("接收到远端track:", event.track);
            this.trackHandle(event.track, event.streams[0]);
          });
        }
      });

      //确认呼叫后激发
      remotedata.session.on("confirmed", () => {
        console.log("onConfirmed - ", remotedata);
        if (remotedata.originator == "remote" && this.currentSession == null) {
          this.currentSession = this.incomingSession;
          this.incomingSession = null;
          console.log("setCurrentSession - ", this.currentSession);
        }
      });

      // 挂断处理
      remotedata.session.on("ended", () => {
        this.endedHandle();
        console.log("call ended:", remotedata);
      });

      remotedata.session.on("failed", (e) => {
        this.$modal.msgError("会话失败");
        console.error("会话失败:", e);
      });
    },
    trackHandle(track, stream) {
      const showVideo = () => {
        navigator.mediaDevices
          .getUserMedia({
            ...this.constraints,
            audio: false, // 不播放本地声音
          })
          .then((stream) => {
            this.meVideo.srcObject = stream;
          })
          .catch((error) => {
            that.$modal.msgError(`${error.name}:${error.message}`);
          });
      };
      // 根据轨道类型选择播放元素
      if (track.kind === "video") {
        // 使用 video 元素播放视频轨道
        this.remoteVideo.srcObject = stream;
        showVideo();
      } else if (track.kind === "audio") {
        // 使用 audio 元素播放音频轨道
        this.audio.srcObject = stream;
      }
    },
    endedHandle() {
      this.clearMedia("meVideo");
      this.clearMedia("remoteVideo");
      this.clearMedia("audio");
      if (this.myHangup) {
        this.$modal.msgSuccess("通话结束");
      } else {
        this.$modal.msgWarning("对方已挂断!");
      }
      this.myHangup = false;

      this.currentSession = null;
    },
    startCall(isVideo = false) {
      if (!this.isValidExtension(this.targetExtension)) {
        this.$modal.msgError("分机号无效,请输入1001-1019之间的分机号");
        return;
      }

      if (this.userAgent) {
        try {
          const eventHandlers = {
            progress: (e) => console.log("call is in progress"),
            failed: (e) => {
              console.error(e);
              this.$modal.msgError(`call failed with cause: ${e.cause}`);
            },
            ended: (e) => {
              this.endedHandle();
              console.log(`call ended with cause: ${e.cause}`);
            },
            confirmed: (e) => console.log("call confirmed"),
          };
          console.log("this.userAgent.call");
          this.outgoingSession = this.userAgent.call(
            `sip:${this.targetExtension}@${this.serverIp}`, // :5060
            {
              mediaConstraints: { audio: true, video: isVideo },
              eventHandlers,
            }
          );
        } catch (error) {
          this.$modal.msgError("呼叫失败");
          console.error("呼叫失败:", error);
        }
      } else {
        this.$modal.msgError("用户代理未初始化");
      }
    },
    hangUpCall() {
      this.myHangup = true;
      this.outgoingSession = this.userAgent.terminateSessions();
      this.currentSession = null;
    },
    clearMedia(mediaNameOrStream) {
      let mediaSrcObject = this[mediaNameOrStream].srcObject;
      if (mediaSrcObject) {
        let tracks = mediaSrcObject.getTracks();
        for (let i = 0; i < tracks.length; i++) {
          tracks[i].stop();
        }
      }
      this[mediaNameOrStream].srcObject = null;
    },
    unregisterUser() {
      console.log("取消注册");
      this.userAgent.unregister();
      this.resetState();
    },
    resetState() {
      this.userExtension = "";
      this.targetExtension = "";
      this.isRegisted = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.test-sip {
  padding: 30px;

  .step {
    margin-bottom: 20px;

    .step-box {
      display: flex;
      align-items: flex-start;
      gap: 20px;

      .input-box {
        width: 350px;
      }

      .step-button {
        align-self: flex-start;
      }

      #meVideo,
      #remoteVideo {
        width: 360px;
        background-color: #333;
      }

      #meVideo {
        border: 2px solid red;
      }

      #remoteVideo {
        border: 2px solid blue;
      }
    }
  }
}
</style>

标签:Vue,console,log,remotedata,JsSIP,音视频,userAgent,null,audio
From: https://blog.csdn.net/qq_44910894/article/details/139642196

相关文章

  • vue3 修改element-plus主题颜色(css版)
    vue3修改主题颜色_若依vue3改默认主题色-CSDN博客上面的是js修改-----------------------------------------------------------------------------------------------------------------------1.新建一个APPStyle.css文件代码/*8这里是要替换的样式,可以参开下面注释......
  • 国思RDIF.vNext全新低代码快速开发框架平台6.1版本发布(支持vue2、vue3)
    1、平台介绍RDIF.vNext,全新低代码快速开发集成框架平台,给用户和开发者最佳的.Net框架平台方案,为企业快速构建跨平台、企业级的应用提供强大支持。RDIF.vNext的前身是RDIFramework框架,RDIF(RapiddevelopIntegrateFramework,vNext代表全新下一代),全新设计,全新开发,代码量减......
  • vue3探索——在setup script中使用tsx语法
    vue3+ts+eslint配置tsxvite.config.ts安装@vitejs/plugin-vue-jsx#npmnpmi@vitejs/plugin-vue-jsx-D#yarnyarnadd@vitejs/plugin-vue-jsx-D#pnpmpnpmadd@vitejs/plugin-vue-jsx-D在vite.config.ts中使用……importvueJsxfrom'@vitejs/plugin-vue......
  • [vue2]深入理解vuex
    本节内容概述初始化仓库定义数据访问数据修改数据处理异步派生数据模块拆分案例-购物车概述vuex是一个vue的状态管理工具,状态就是数据场景某个状态在很多个组件使用(个人信息)多个组件共同维护一份数据(购物车)优势数据集中式管理数据响应式变化初始化仓库......
  • java基于Vue+Spring boot前后端分离架构开发的一套UWB技术高精度定位系统源码
    java基于Vue+Springboot前后端分离架构开发的一套UWB技术高精度定位系统源码系统采用UWB高精度定位技术,可实现厘米级别定位。UWB作为一种高速率、低功耗、高容量的新兴无线局域定位技术,目前应用主要聚焦在室内外精确定位。在工业自动化、物流仓储、电力巡检、煤矿施工、自动......
  • Vue2入门之超详细教程十八-自定义指令
    Vue2入门之超详细教程十四-自定义指令1、简介定义语法分为局部自定义指令和全局自定义指令配置对象中常用的3个回调bind:指令与蒜素被插入成功时调用inserted:指令所在元素被插入页面时被调用update:指令所在模板结构被重新解析时调用备注:指令定义时不加v-,但使用时......
  • Vue3——toRef和toRefs
    toRef和toRefs作用toRef和toRefs功能相同,都是将一个响应式对象中的每个属性,转成ref对象,但是toRefs可以批量转换。语法:>lettemp=toRef(对象.属性名)和let{temp1,temp2,temp3,...}=toRefs(对象)模版中使用运行结果代码<template><divclass="root"><h......
  • 个人关于vuex的见解
    前言vuex是什么?Vuex是Vue.js的官方状态管理库,专为Vue.js应用程序设计,用于在复杂的前端应用中集中管理状态。Vuex的重要性集中管理:统一存储应用状态,简化复杂应用的状态逻辑。响应式更新:状态变更自动反映到所有依赖组件,保持UI与状态同步。预测性:状态变更通过mutatio......
  • 【FFmpeg】SDL 音视频开发 ② ( SDL 视频显示函数 | 设置渲染器目标纹理 | 设置渲染器
    文章目录一、SDL视频显示函数1、SDL的渲染器和纹理之间的关系2、SDL_SetRenderTarget函数-设置渲染器目标纹理3、SDL_SetRenderDrawColor函数-设置渲染器颜色4、SDL_RenderClear函数-清除渲染器5、SDL_RenderDrawRect函数-渲染器绘制矩形6、SDL_Render......
  • 基于python+vue的贫困生资助系统
    博主介绍:java高级开发,从事互联网行业六年,熟悉各种主流语言,精通java、python、php、爬虫、web开发,已经做了多年的设计程序开发,开发过上千套设计程序,没有什么华丽的语言,只有实实在在的写点程序。......