Web网页音视频通话之基于Sipjs

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。Web网页音视频通话之基于Sipjs,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

简述
本文是以FreeSwitch作为信令服务器,通过sipjs(基于webRtc) 进行媒体协商,网络协商后,进行P2P媒体传输。

参考知识:

效果图

Web网页音视频通话之基于Sipjs

HTML

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <title>视频通话demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <link rel="shortcut icon" th:href="@{/ico/logo.ico}" type="image/x-icon" />
    <link rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <link rel="stylesheet" th:href="@{/css/baiban.css}">
    <script th:inline="javascript">
        const pub = [[${pub}]];
    </script>
</head>
<body>
<div id="app">
    <!--头部导航-->
    <ul class="layui-nav layui-bg-blue" lay-bar="disabled">
        <li class="layui-nav-item"><a target="_blank">视频通话</a></li>
    </ul>
    <!--音视频通话-->
    <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
        <legend>音视频通话</legend>
    </fieldset>
    <div class="layui-row" style="border: 1px solid  #f0f0f0;margin-left: 10px;margin-right: 10px;padding-top: 10px">
        <div class="layui-col-xs12 layui-col-md4" >
            <form class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">我的号码:</label>
                        <div class="layui-input-inline">
                            <input id="myNumber" value="1000" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">信令地址:</label>
                        <div class="layui-input-inline">
                            <input id="sipAddr" th:value="${fs}" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">Websocket端口:</label>
                    <div class="layui-input-block">
                        <input type="radio" name="wsUrl" value="5066" title="http" checked>
                        <input type="radio" name="wsUrl" value="7443" title="https">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">拨打号码</label>
                        <div class="layui-input-inline">
                            <input id="sip_phone_number" value="1001" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                </div>
                <div class="layui-form-item" style="text-align: center">
                    <div class="layui-inline">
                        <button type="button" class="layui-btn layui-btn-primary" onclick="softPhone.start()"
                                id="register">注册
                        </button>
                        <button type="button" class="layui-btn layui-btn-normal operate layui-btn-disabled" disabled
                                onclick="PHONE.call()" id="call">拨打
                        </button>
                        <button type="button" class="layui-btn layui-btn-normal operate layui-btn-disabled" disabled
                                onclick="PHONE.hangUp()" id="hangup">挂断
                        </button>   
                </div>
            </form>
        </div>
        <!--视频展示区-->
        <div class="layui-col-xs12 layui-col-md4" style="border:5px solid #3385FF;width: 615px;height: 600px">
            <div id="playVideo">
                <video id="youVideo" style="padding-right:10px" width="600px" height="600px" muted autoplay
                       onmousedown="move(this)" th:poster="@{/img/webrtc.png}"
                       playsinline></video>
            </div>
            <div style="position:relative;top:-168px;left:1px">
                <video id="meVideo" width="100px" height="100px" th:poster="@{/img/webrtc.png}" autoplay playsinline></video>
            </div>
        </div>
    </div>
</div>
<canvas id="capture" style="display: none"></canvas>
<script th:src="@{/javascript/jquery-2.1.4.js}" type="application/javascript"></script>
<script th:src="@{/javascript/sip-0.15.10.js}" type="application/javascript"></script>
<script th:src="@{/layui/layui.js}" type="application/javascript"></script>
<!--操作-->
<script th:src="@{/javascript/sip-pc/operation.js}" type="application/javascript"></script>

javaScript

  let table = null;
    let form = null;
    let layer = null;
    let laydate = null;
    let upload = null;
    // 拨打电话确认框
    let confirmIndex = null;
    layui.use(['table', 'form', 'layer', 'laydate', 'upload'], function () {
        $(function () {
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            upload = layui.upload;
            if (window.location.protocol === 'http:') {
                $('input[name="wsUrl"][value="5066"]').attr("checked", true);
            } else {
                $('input[name="wsUrl"][value="7443"]').attr("checked", true);
            }
        });
    });

    // 本地视频
    var localVideo = document.getElementById('meVideo');
    // 远端视频
    var remoteVideo = document.getElementById('youVideo');

    var softPhoneUA = null;
    var currentSession = null;

    /**
     * 注册模块
     * @type {{logout(): void, start(): void, unregister(): void, UAEvent(*): void, register(): void, sessionEvent(*): void}}
     */
    const softPhone = {
        /**
         * 登陆软电话
         */
        start() {
            // 获取我的号码
            var myNumber = $.trim($('#myNumber').val());
            // 获取sip地址
            var sipAddr = $.trim($('#sipAddr').val());
            // sip url 拼接
            var sip_uri = myNumber + '@' + sipAddr
            // 信令密码
            var sip_password = $.trim($('#sipPassword').val());
            // 获取WS连接端口
            var wsPort = $.trim($('input[name="wsUrl"]:checked').val());
            // var wsPort = "5060";
            var ws_uri = wsPort == '5066' ? 'ws://' + sipAddr + ':' + wsPort : 'wss://' + sipAddr + ':' + wsPort

            var config = {
                uri: sip_uri,
                transportOptions: {
                    wsServers: [ws_uri]
                },
                // 授权号
                authorizationUser: myNumber,
                // 登陆密码
                password: '1234',
                displayName: myNumber,
                register: true
            };
            //v 就绪软电话、监听软电话连接状态、监听电话呼入、拨打电话、登出软电话系统
            softPhoneUA = new SIP.UA(config);
            softPhone.UAEvent(softPhoneUA);
            // 有电话呼入
            softPhoneUA.on('invite', function (session) {
                currentSession = session;
                softPhone.sessionEvent(session);
                layer.confirm('有电话呼入 ... 请注意是否接听)', {
                    btn: ['取消', '接听', '拒绝'],
                    btn1: function () {
                        layer.close(index);
                    },
                    btn2: function () {
                        PHONE.answer();
                    },
                    btn3: function () {
                        softPhone.hangUp();
                    }
                });
            })
        },

        /** 就绪 */
        register() {
            softPhoneUA.register({  // 注册
                register: true
            });
        },

        /**
         * 绑定ua事件
         * @param {*} ua
         */
        UAEvent(ua) {
            // 开始尝试连接
            ua.on('connecting', function (args) {
                console.log('%c connecting - 开始尝试连接', 'color: #f00');
            });
            // 连接完毕
            ua.on('connected', function () {
                console.log('%c connected - 连接完毕', 'color: #f00');
            });
            // 主动取消注册或注册后定期重新注册失败
            ua.on('unregistered', function (response, cause) {
                $('#register').removeClass("layui-btn-disabled").removeAttr('disabled');
                console.log('%c unregistered - 主动取消注册或注册后定期重新注册失败', 'color: #f00');
            });
            // 注册成功
            ua.on('registered', function () {
                layer.msg("注册成功", {icon: 1, time: 1500});
                console.log('%c registered -- 注册成功', 'color: #f00');
                btnHide(['register','shard'])
                btnShow(['call'])
            })
            // websocket 连接失败
            ua.on('disconnected', function () {
                console.log('%c disconnected - 连接失败', 'color: #f00');
            })
        },

        /**
         * 绑定session事件
         * @param {} session
         */
        sessionEvent(session) {
            session.on("rejected", function (response, cause) {
                layer.close(confirmIndex);
            });
            session.on("bye", function (response, cause) {
                // 不可用
                btnHide(['hangup','mute','unmute','openVideo','closeVideo','shard'])
                localVideo.srcObject = null;
                remoteVideo.srcObject = null;
            });
            // 会话被接入
            session.on("accepted", function (response, cause) {
                layer.close(confirmIndex);
                btnShow(['hangup','mute','unmute','openVideo','closeVideo','shard','capturePic'])
                var pc = session.sessionDescriptionHandler.peerConnection;
                var remoteStream = new MediaStream();
                pc.getReceivers().forEach(function (receiver) {
                    remoteStream.addTrack(receiver.track);
                });
                remoteVideo.srcObject = remoteStream;
                if (pc.getSenders()) {
                    var localStream = new MediaStream();
                    pc.getSenders().forEach(function (sender) {
                        localStream.addTrack(sender.track);
                    });
                    localVideo.srcObject = localStream;
                }
            });
            session.on("cancel", function (response, cause) {
                layer.close(confirmIndex);
            });
        }
    }

operation.js

/**
 *  拨打、接听、挂断 模块
 * @type {{call(): void, answer(): void, hangUp(): void}}
 */
const PHONE = {
    /**
     * 拨打
     */
    call() {
        const telNumber = $.trim($('#sip_phone_number').val());
        var sipAddr = $.trim($('#sipAddr').val());
        const inviteUrl = telNumber + '@' + sipAddr
        currentSession = softPhoneUA.invite(inviteUrl, {
            sessionDescriptionHandlerOptions: {
                constraints: {
                    audio: {
                        autoGainControl: true,
                        // 噪音消除
                        noiseSuppression: true,
                        // 设置降噪
                        echoCancellation: true
                    },
                    video: true
                },
                alwaysAcquireMediaFirst: true // 此参数是sip.js官方修复在firefox遇到的bug所设置
        })
        confirmIndex = layer.confirm('呼叫中....', {
            btn: ['取消'],
            btn1: function (index) {
                currentSession.cancel();
                layer.close(index);
            }
        });
        // 拨打后 监听
        currentSession.on("rejected", function (response, cause) {
            layer.msg("请求通话被拒绝", {icon: 1, time: 1500});
            console.log(response)
            console.log(cause)
        });
        // 本次通话结束
        currentSession.on("bye", function (response, cause) {
            layer.msg("本次通话结束", {icon: 1, time: 1500});
            localVideo.srcObject = null;
            remoteVideo.srcObject = null;
        });
        // 对方接听
        currentSession.on("accepted", function (response, cause) {
            layer.msg("对方接听", {icon: 1, time: 1500});
            $('#call').addClass('layui-btn-disabled').attr('disabled', 'disabled');
            $('#hangup').removeClass('layui-btn-disabled').removeAttr('disabled');
            $('#mute').removeClass('layui-btn-disabled').removeAttr('disabled');
            $('#unmute').removeClass('layui-btn-disabled').removeAttr('disabled');
            var pc = currentSession.sessionDescriptionHandler.peerConnection;
            var remoteStream = new MediaStream();
            pc.getReceivers().forEach(function (receiver) {
                remoteStream.addTrack(receiver.track);
            });
            remoteVideo.srcObject = remoteStream;
            if (pc.getSenders()) {
                var localStream = new MediaStream();
                pc.getSenders().forEach(function (sender) {
                    localStream.addTrack(sender.track);
                });
                localVideo.srcObject = localStream;
            }
        });
        // 取消通话
        currentSession.on("cancel", function (response, cause) {
            layer.msg("取消通话", {icon: 1, time: 1500});
        });
    },
    /**
     * 挂断
     */
    hangUp() {
        if (currentSession instanceof Object) {
            if (currentSession.hasAnswer) {
                currentSession.bye();
            } else if (currentSession.isCanceled === false) {
                currentSession.cancel();
            } else {
                currentSession.reject();
            }
        }
    },
    /**
     * 接听
     */
    answer() {
        var option = {
            sessionDescriptionHandlerOptions: {
                constraints: {
                    audio: {
                        autoGainControl: true,
                        // 噪音消除
                        noiseSuppression: true,
                        // 设置降噪
                        echoCancellation: true
                    },
                    video: true
                },
                alwaysAcquireMediaFirst: true, // 此参数是sip.js官方修复在firefox遇到的bug所设置
                rtcConfiguration: {
                    iceServers: [
                        {
                            url: "stun:124.222.83.153:3478",
                            username: "test",//可选
                            credential: "test123"//可选
                        },
                        {
                            url: "turn:124.222.83.153:3478",
                            "username": "test",//可选
                            "credential": "test123"//可选
                        }
                    ]
                }
            }
        }
        currentSession.accept(option)
    }
}

拨打

Web网页音视频通话之基于Sipjs

接听

Web网页音视频通话之基于Sipjs

通话中

Web网页音视频通话之基于Sipjs

数据流程图

Web网页音视频通话之基于Sipjs

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/197569.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!