WebRTC + JsSIP + freeSWITCH一对一语音聊天

版权声明:本文为CSDN博主「foruok」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/foruok/article/details/74321214

之前几篇文件介绍了 freeSWITCH 和 WebRTC 结合在一起需要的各种环境,现在到了最关键的一篇,使用 JsSIP 来创建一个 DEMO 。这次我们需要写点 JS 代码。

准备 JsSIP 库文件
可以从 http://www.jssip.net/download/ 下载一个 min 版的 js 文件,我用的是 3.0.13 ,文件名是 jssip-3.0.13.min.js ,把它放在我们之前用 Node.js 建立的 https 服务器的 public/js 目录下,我们将在 html 文件内引用它。类似:

<script src="js/jssip-3.0.13.min.js" type="text/javascript"></script> 

配置 freeSWITCH
我们之前下载的 freeSWITCH ,默认是不处理音视频编解码的,所以,要设置它采用 media proxy 模式来代理转发 WebRTC 的音视频,这样就可以基于 JsSIP 、 WebRTC 、 freeSWITCH 来一对一视频聊天。

修改vars.xml,加入:

 <X-PRE-PROCESS cmd=="set" data="proxy_media=true"/>

修改sip_profiles/internal.xml,设置inbound-proxy-media和inbound-late-negotiation为true,类似下面:

<!--Uncomment to set all inbound calls to proxy media mode-->
    <param name="inbound-proxy-media" value="true"/>

    <!-- Let calls hit the dialplan before selecting codec for the a-leg -->
    <param name="inbound-late-negotiation" value="true"/>

这样配置之后,freeSWITCH 会进入代理模式,不对media 做任何处理,直接在两个 end peer 之间转发(RTP包)。

JsSIP DEMO
JsSIP 的 API 文档参考下面链接:

http://www.jssip.net/documentation/3.0.x/api/
http://www.jssip.net/documentation/3.0.x/api/session/
http://www.jssip.net/documentation/3.0.x/api/ua/
注意, JsSIP 对 SIP 和 WebRTC 做了封装,比如你不需要自己调用 getUserMedia 来捕获音视频了, JsSIP 会根据你传给JsSIP.UA.call方法的参数来自己调用,用起来比较方便。

但是,你还是要了解 SIP 呼叫的流程和WebRTC的各种限制以及如何处理 RTCPeerConnection 发过来的音视频流。

关于 WebRTC JS 侧 API,看这里好了:http://w3c.github.io/webrtc-pc/

想看更多资料,可以看我搜集的这些链接:WebRTC学习资料大全

关于 SIP 的流程,参考《freeSWITCH权威指南》这本书吧,讲得很明白。

网上关于 JsSIP + freeSWITCH 的 demo 很少,而且基本跑不起来……我这个是验证过的啦!

直接给出我们的 demo.html 的所有代码:

<!DOCTYPE html>
<html>
<head>
    <title>JsSIP + WebRTC + freeSWITCH</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="Author" content="foruok" />
    <meta name="description" content="JsSIP based example web application." />
    <script src="./jssip-3.3.11.min.js" type="text/javascript"></script>
    <style type="text/css">
    </style>
</head>


<body>

<div id="login-page" style="width: 424px; height: 260px; background-color: #f2f4f4; border: 1px solid grey; padding-top: 4px">
    <table border="0" frame="void" width="418px">
        <tr>
            <td class="td_label" width="160px" align="right"><label for="sip_uri">SIP URI:</label></td>
            <td width="258px"><input style="width:250px" id="sip_uri" type="text" placeholder="SIP URI (i.e: sip:alice@example.com)" value=""/></td>
        </tr>
        <tr>
            <td class="td_label"  align="right"><label for="sip_password">SIP Password:</label></td>
            <td><input style="width:250px" id="sip_password" type="password" placeholder="SIP password" value=""/></td>
        </tr>
        <tr>
            <td class="td_label" align="right"><label for="ws_uri">WSS URI:</label></td>
            <td><input style="width:250px" id="ws_uri" class="last unset" type="text" placeholder="WSS URI (i.e: wss://example.com)" value=""/></td>
        </tr>
        <tr>
            <td class="td_label"  align="right"><label class="input_label" for="sip_phone_number">SIP Phone Info:</label></td>
            <td><input style="width:250px" id="sip_phone_number" type="text" placeholder="sip:3000@192.168.40.96:5060" value=""></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><button onclick="testStart()"> Initialize </button></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><button onclick="testCall()"> Call </button></td>
        </tr>
        <tr>
            <td  colspan="2" align="center"><button onclick="captureLocalMedia()"> Capture Local Media</button></td>
        </tr>
    </table>
</div>

<div style="width: 424px; height: 324px;background-color: #333333; border: 2px solid blue; padding:0px; margin-top: 4px;">
    <video id="video" width="420px" height="320px" autoplay ></video>
    <audio id="audio" controls></audio>
</div>

</body>
<script type="text/javascript">
  var outgoingSession = null;
  var incomingSession = null;
  var currentSession = null;
  var audio = document.getElementById('audio');

  var constraints = {
    audio: true,
    video: true,
    mandatory: {
      maxWidth: 640,
      maxHeight: 360
    }
  };
  URL = window.URL || window.webkitURL;

  var localStream = null;
  var userAgent = null;

  function gotLocalMedia(stream) {
    console.info('Received local media stream');
    localStream = stream;
    audio.src = URL.createObjectURL(stream);
  }

  function captureLocalMedia() {
    console.info('Requesting local video & audio');
    navigator.webkitGetUserMedia(constraints, gotLocalMedia, function(e){
      alert('getUserMedia() error: ' + e.name);
    });
  }

  function testStart(){

    var sip_uri_ = document.getElementById("sip_uri").value.toString();
    var sip_password_ = document.getElementById("sip_password").value.toString();
    var ws_uri_ = document.getElementById("ws_uri").value.toString();

    console.info("get input info: sip_uri = ", sip_uri_, " sip_password = ", sip_password_, " ws_uri = ", ws_uri_);

    var socket = new JsSIP.WebSocketInterface(ws_uri_);
    var configuration = {
      sockets: [ socket ],
      outbound_proxy_set: ws_uri_,
      uri: sip_uri_,//与用户代理关联的SIP URI(字符串)。这是您的提供商提供给您的SIP地址
      password: sip_password_,//SIP身份验证密码
      register: true,//指示启动时JsSIP用户代理是否应自动注册
      session_timers: false//启用会话计时器(根据RFC 4028)
    };

    userAgent = new JsSIP.UA(configuration);

    //成功注册成功,data:Response JsSIP.IncomingResponse收到的SIP 2XX响应的实例
    userAgent.on('registered', function(data){
      console.info("registered: ", data.response.status_code, ",", data.response.reason_phrase);
    });
    //由于注册失败而被解雇,data:Response JsSIP.IncomingResponse接收到的SIP否定响应的实例,如果失败是由这样的响应的接收产生的,否则为空
    userAgent.on('registrationFailed', function(data){
      console.log("registrationFailed, ", data);
      //console.warn("registrationFailed, ", data.response.status_code, ",", data.response.reason_phrase, " cause - ", data.cause);
    });

    //1.在注册到期之前发射几秒钟。如果应用程序没有为这个事件设置任何监听器,JsSIP将像往常一样重新注册。
    // 2.如果应用程序订阅了这个事件,它负责ua.register()在registrationExpiring事件中调用(否则注册将过期)。
    // 3.此事件使应用程序有机会在重新注册之前执行异步操作。对于那些在REGISTER请求中的自定义SIP头中使用外部获得的“令牌”的环境很有用。
    userAgent.on('registrationExpiring', function(){
      console.warn("registrationExpiring");
    });

    //为传入或传出会话/呼叫激发。data:
    //     originator:'remote',新消息由远程对等方生成;'local',新消息由本地用户生成。
    //      session:JsSIP.RTCSession 实例。
    //      request:JsSIP.IncomingRequest收到的MESSAGE请求的实例;JsSIP.OutgoingRequest传出MESSAGE请求的实例
    userAgent.on('newRTCSession', function(data){
      console.info('onNewRTCSession: ', data);
      if(data.originator == 'remote'){ //incoming call
        console.info("incomingSession, answer the call");
        incomingSession = data.session;
        //回答传入会话。此方法仅适用于传入会话。
        data.session.answer({'mediaConstraints' : { 'audio': true, 'video': true },
         // 'mediaStream': localStream
        });
      }else{
        console.info("outgoingSession");
        outgoingSession = data.session;
        outgoingSession.on('connecting', function(data){
          console.info('onConnecting - ', data.request);
          currentSession = outgoingSession;
          outgoingSession = null;
        });
      }
      //接受呼叫时激发
      data.session.on('accepted', function(data){
        console.info('onAccepted - ', data);
        if(data.originator == 'remote' && currentSession == null){
          currentSession = incomingSession;
          incomingSession = null;
          console.info("setCurrentSession - ", currentSession);
        }
      });
      //确认呼叫后激发
      data.session.on('confirmed', function(data){
        console.info('onConfirmed - ', data);
        if(data.originator == 'remote' && currentSession == null){
          currentSession = incomingSession;
          incomingSession = null;
          console.info("setCurrentSession - ", currentSession);
        }
      });
      //在将远程SDP传递到RTC引擎之前以及在发送本地SDP之前激发。此事件提供了修改传入和传出SDP的机制。
      data.session.on('sdp', function(data){
        console.info('onSDP, type - ', data.type, ' sdp - ', data.sdp);
        //data.sdp = data.sdp.replace('UDP/TLS/RTP/SAVPF', 'RTP/SAVPF');
        //console.info('onSDP, changed sdp - ', data.sdp);
      });
      //接收或生成对邀请请求的1XX SIP类响应(>100)时激发。该事件在SDP处理之前触发(如果存在),以便在需要时对其进行微调,甚至通过删除数据对象中响应参数的主体来删除它
      data.session.on('progress', function(data){
        console.info('onProgress - ', data.originator);
        if(data.originator == 'remote'){
          console.info('onProgress, response - ', data.response);
        }
      });
      //创建基础RTCPeerConnection后激发。应用程序有机会通过在peerconnection上添加RTCDataChannel或设置相应的事件侦听器来更改peerconnection。
      data.session.on('peerconnection', function(data){
        console.info('onPeerconnection - ', data.peerconnection);
        data.peerconnection.onaddstream = function(ev){
          console.info('onaddstream from remote - ', ev);
          audio.src = URL.createObjectURL(ev.stream);
          audio.onloadstart = () => {
           audio.play();
          };
          audio.onerror = () => {
           alert('录音加载失败...');
          };
        };
      });
    });
    //为传入或传出消息请求激发。data:
    //     originator:'remote',新消息由远程对等方生成;'local',新消息由本地用户生成。
    //      message:JsSIP.Message 实例。
    //      request:JsSIP.IncomingRequest收到的MESSAGE请求的实例;JsSIP.OutgoingRequest传出MESSAGE请求的实例
    userAgent.on('newMessage', function(data){
      if(data.originator == 'local'){
        console.info('onNewMessage , OutgoingRequest - ', data.request);
      }else{
        console.info('onNewMessage , IncomingRequest - ', data.request);
      }
    });

    console.info("call register");
    //连接到信令服务器,并恢复以前的状态,如果以前停止。重新开始时,如果UA配置中的参数设置为register:true,则向SIP域注册。
    userAgent.start();
  }

  // Register callbacks to desired call events
  var eventHandlers = {
    'progress': function(e) {
      console.log('call is in progress');
    },
    'failed': function(e) {
      console.log('call failed: ', e);
    },
    'ended': function(e) {
      console.log('call ended : ', e);
    },
    'confirmed': function(e) {
      console.log('call confirmed');
    }
  };

  function testCall(){
    var sip_phone_number_ = document.getElementById("sip_phone_number").value.toString();

    var options = {
      'eventHandlers'    : eventHandlers,
      'mediaConstraints' : { 'audio': true, 'video': false ,
      },
      //'mediaStream': localStream
    };

    //outgoingSession = userAgent.call('sip:3000@192.168.40.96:5060', options);
    /*
           * 拨打多媒体电话。不需要自己调用 getUserMedia 来捕获音视频了, JsSIP 会根据你传给JsSIP.UA.call方法的参数来自己调用

               参数

               Target 通话的目的地。String表示目标用户名或完整的SIP URI或JsSIP.URI实例。

               Options 可选Object附加参数(见下文)。
                   options对象中的字段;
                   mediaConstraints Object有两个有效的字段(audio和video)指示会话是否打算使用音频和/或视频以及要使用的约束。默认值是audio并且video设置为true。
                   mediaStream MediaStream 传送到另一端。
                   eventHandlers Object事件处理程序的可选项将被注册到每个呼叫事件。为每个要通知的事件定义事件处理程序。
               */
    outgoingSession = userAgent.call(sip_phone_number_, options);
  }
</script>
</html>

 注意:我用的3.3.11和原作者有点不同

session.on('peerconnection')事件没有触发
//我又添加了另一个事件,能拿到远程的音频流
data.session.connection.addEventListener("addstream", function (ev) {
        console.info('onaddstream from remote - ', ev.stream);
        audio.srcObject  = ev.stream;
      });

 

关于 JsSIP.UA 和 JsSIP.RTCSession 等类和 API 的使用,参考代码,对照 JsSIP 的官方文档,即可理解。

注意我在代码里调用 RTCSession 的 answer 方法做了自动接听。实际开发中,你需要弹出一个提示框,让用户选择是否接听。

一对一视频聊天的效果:
先运行 freeSWITCH , 验证启动正常(参看freeSWITCH安装、配置与局域网测试),再运行 npm start启动 https 服务器,最后 Chrome 内访问 https://192.168.40.131:8080/demo.html ,看到下面的结果:

注意,必须填写有效信息,然后先点击 Initialize 来初始化,代码中会到 freeSWITCH 那里注册 SIP 号码,然后才可以呼叫别人。

被呼叫方只需要填写信息,点击 Initialize 按钮,不需要点击 Call 按钮。

填写所有参数,点击 Initialize 按钮,可以注册一个 SIP 号码 1000(使用开发者工具可查看我输出的日志)。

然后到另一台电脑访问同一个链接,注册一个不同的账号 1002。

再回到初始的那台电脑,在 SIP Phone Info 后输入 sip:1002@192.168.40.131:5060,然后点击 Call 按钮,即可呼叫 1002 ,接通后,可以看到对方视频。效果如下:

这是我们使用 JsSIP 和 freeSWITCH 构建视频聊天的简单 DEMO 。

想起来一点非常重要的:freeSWITCH 和 nodejs 实现的 https 服务器,使用的证书应该是一个,否则会报错哦。可以先跑 freeSWITCH ,然后把 cert/wss.pem 文件的内容分拆给 nodejs 使用。

posted @ 2019-12-12 16:55  Jade_g  阅读(6928)  评论(1编辑  收藏  举报