Внедрение браузерного SIP телефона
в web-страницу
Для того чтобы встроить браузерный телефон на свою web-страницу, используется простой HTML код и специальные скрипты — зависимости, которые обеспечивают работу с микрофоном и соединение с Web Call Server
Для быстрой установки и настройки WCS сервера воспользуйтесь этой инструкцией. Кроме этого, для тестирования вы можете подключиться к нашему демо-серверу demo.flashphoner.com
Пошаговая инструкция по внедрению
браузерного SIP телефона в web-страницу
Браузерный SIP телефон возможен в двух вариантах — с поддержкой видеозвонка и без поддержки видеозвонка. Ниже рассмотрим подробно процесс внедрения обоих вариантов.
Вариант 1. SIP телефон без видеозвонка
Для внедрения SIP телефона без видеозвонка на свою web-страницу, создадим два пустых файла phone-min.html и phone-min.js. Эти файлы будут содержать минимальный код.
Разберем содержимое файлов
HTML
Разместим в phone-min.html необходимые элементы:
1. Импортируем скрипт основного API
1 | <script type = "text/javascript" src= "https://flashphoner.com/downloads/builds/flashphoner_client/wcs_api-2.0/current/flashphoner.js" >< /script > |
2. Импортируем скрипт SIP телефона
1 | <script type = "text/javascript" src= "phone-min.js" >< /script > |
3. Инициализируем API на загрузку страницы
1 | <body onload= "init_page()" > |
4. Добавляем поле для ввода SIP номера вызываемого абонента
1 | <input id = "callee" type = "text" placeholder= "Callee SIP username" /> |
5. Добавляем кнопку «Call» для совершения исходящего SIP вызова
1 | <button type = "button" onclick= "call()" >Call< /button > |
6. Добавляем div-элемент для сообщения о входящем звонке
1 | <div id = "status" >< /div > |
7. Добавляем кнопку для ответа на входящий звонок и кнопку завершения вызова
1 2 | <button id = "answerBtn" type = "button" >Answer< /button > <button id = "hangupBtn" type = "button" >Hangup< /button > |
8. Добавляем два div-элемента в которых будет проигрываться звук
1 2 | <div id = "localAudio" >< /div > <div id = "remoteAudio" >< /div > |
Полный код HTML — страницы выглядит так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html lang= "en" > < head > <meta charset= "utf-8" > <script type = "text/javascript" src= "https://flashphoner.com/downloads/builds/flashphoner_client/wcs_api-2.0/current/flashphoner.js" >< /script > <script type = "text/javascript" src= "phone-min.js" >< /script > < /head > <body onload= "init_page()" > <input id = "callee" type = "text" placeholder= "Callee SIP username" /> <button type = "button" onclick= "call()" >Call< /button > <br> <div id = "status" >< /div > <button id = "answerBtn" type = "button" >Answer< /button > <button id = "hangupBtn" type = "button" >Hangup< /button > <div id = "localAudio" >< /div > <div id = "remoteAudio" >< /div > < /body > < /html > |
JavaScript
1. Создаем константы для статуса работы WCS и SIP сервера
1 2 | var SESSION_STATUS = Flashphoner.constants.SESSION_STATUS; var CALL_STATUS = Flashphoner.constants.CALL_STATUS; |
2. Создаем глобальные переменные для аудио потока и текущего звонка
1 2 3 | var localAudio; var remoteAudio; var currentCall; |
3. При загрузке HTML страницы инициализируем API, получаем div-элементы для проигрывания аудио и вызываем функцию «connect()», которая обеспечивает подключение к WCS и SIP серверу и ожидание входящего звонка.
1 2 3 4 5 6 | function init_page() { Flashphoner.init({}); localAudio = document.getElementById( "localAudio" ); remoteAudio = document.getElementById( "remoteAudio" ); connect(); } |
4. В функции «connect()» объявляем переменные для параметров подключения к WCS и SIP серверам. Для корректной работы вам следует заменить значения на свои. URL — адрес вашего WCS, sipOptions — данные для подключения к вашему SIP серверу. После объявления переменных, функция запускает соединение с WCS и SIP серверами
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | function connect() { var url = "wss://demo.flashphoner.com:8443" var registerRequired = true ; var sipOptions = { login: "10001" , authenticationName: "10001" , password: "Pass123" , domain: "your_sip_server.com" , outboundProxy: "your_sip_server.com" , port: "5060" , registerRequired: registerRequired }; var connectionOptions = { urlServer: url, sipOptions: sipOptions }; //create session console.log( "Create new session with url " + url); Flashphoner.createSession(connectionOptions).on(SESSION_STATUS.ESTABLISHED, function (session) { console.log(SESSION_STATUS.ESTABLISHED); }).on(SESSION_STATUS.REGISTERED, function (session) { console.log(SESSION_STATUS.REGISTERED); }).on(SESSION_STATUS.INCOMING_CALL, function (call) { call.on(CALL_STATUS.RING, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.RING); }).on(CALL_STATUS.ESTABLISHED, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.ESTABLISHED); }).on(CALL_STATUS.FINISH, function () { document.getElementById( "status" ).textContent = ( " " ); console.log(CALL_STATUS.FINISH); currentCall = null; }); onIncomingCall(call); }); } |
5. Функция «call()» обеспечивает работу исходящего звонка.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function call() { var session = Flashphoner.getSessions()[0]; var constraints = getConstraints(); var callee = document.getElementById( "callee" ).value; var outCall = session.createCall({ callee: callee, remoteVideoDisplay: remoteAudio, localVideoDisplay: localAudio, constraints: constraints, stripCodecs: "SILK" }); outCall.call(); currentCall = outCall; hangupBtn.onclick = function () { outCall.hangup(); currentCall = null; } } |
6. Функция «onIncomingCall(inCall)» обеспечивает прием входящего звонка
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function onIncomingCall(inCall) { currentCall = inCall; var constraints = getConstraints(); answerBtn.onclick = function () { inCall.answer({ localVideoDisplay: localAudio, remoteVideoDisplay: remoteAudio, constraints: constraints, stripCodecs: "SILK" }); }; hangupBtn.onclick = function () { inCall.hangup(); currentCall = null; } } |
7. Функция «getConstraints()» задает параметры потока. В нашем текущем примере браузерный SIP телефон без видеозвонка, поэтому для параметра «video» указываем значение «false»
1 2 3 4 5 6 7 | function getConstraints() { var constraints = { audio: true , video: false , }; return constraints; } |
Полный код JavaScript выглядит так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | var SESSION_STATUS = Flashphoner.constants.SESSION_STATUS; var CALL_STATUS = Flashphoner.constants.CALL_STATUS; var localAudio; var remoteAudio; var currentCall; function init_page() { Flashphoner.init({}); localAudio = document.getElementById( "localAudio" ); remoteAudio = document.getElementById( "remoteAudio" ); connect(); } function connect() { var url = "wss://demo.flashphoner.com:8443" var registerRequired = true ; var sipOptions = { login: "10001" , authenticationName: "10001" , password: "Pass123" , domain: "your_sip_server.com" , outboundProxy: "your_sip_server.com" , port: "5060" , registerRequired: registerRequired }; var connectionOptions = { urlServer: url, sipOptions: sipOptions }; //create session console.log( "Create new session with url " + url); Flashphoner.createSession(connectionOptions).on(SESSION_STATUS.ESTABLISHED, function (session) { console.log(SESSION_STATUS.ESTABLISHED); }).on(SESSION_STATUS.REGISTERED, function (session) { console.log(SESSION_STATUS.REGISTERED); }).on(SESSION_STATUS.INCOMING_CALL, function (call) { call.on(CALL_STATUS.RING, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.RING); }).on(CALL_STATUS.ESTABLISHED, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.ESTABLISHED); }).on(CALL_STATUS.FINISH, function () { document.getElementById( "status" ).textContent = ( " " ); console.log(CALL_STATUS.FINISH); currentCall = null; }); onIncomingCall(call); }); } function call() { var session = Flashphoner.getSessions()[0]; var constraints = getConstraints(); var callee = document.getElementById( "callee" ).value; var outCall = session.createCall({ callee: callee, remoteVideoDisplay: remoteAudio, localVideoDisplay: localAudio, constraints: constraints, stripCodecs: "SILK" }); outCall.call(); currentCall = outCall; hangupBtn.onclick = function () { outCall.hangup(); currentCall = null; } } function onIncomingCall(inCall) { currentCall = inCall; var constraints = getConstraints(); answerBtn.onclick = function () { inCall.answer({ localVideoDisplay: localAudio, remoteVideoDisplay: remoteAudio, constraints: constraints, stripCodecs: "SILK" }); }; hangupBtn.onclick = function () { inCall.hangup(); currentCall = null; } } function getConstraints() { var constraints = { audio: true , video: false , }; return constraints; } |
Вид телефона при входящем звонке
Вид телефона при исходящем звонке
Вариант 2. SIP телефон с видеозвонком
Для внедрения SIP телефона с поддержкой видеозвонка на свою web-страницу, создадим два пустых файла phone-video-min.html и phone-video-min.js. Эти файлы будут содержать минимальный код.
Разберем содержимое файлов
HTML
Разместим в phone-video-min.html необходимые элементы:
1. Импортируем скрипт основного API
1 | <script type = "text/javascript" src= "https://flashphoner.com/downloads/builds/flashphoner_client/wcs_api-2.0/current/flashphoner.js" >< /script > |
2. Импортируем скрипт SIP телефона
1 | <script type = "text/javascript" src= "phone-video-min.js" >< /script > |
3. Указываем стили для класса «display». Это нужно для дальнейшего корректного отображения видео в div-элементах
1 2 3 4 5 6 7 8 9 10 11 12 | <style> .display { width: 100%; height: 100%; display: inline-block; } .display > video, object { width: 100%; height: 100%; } < /style > |
4. Инициализируем API на загрузку страницы
1 | <body onload= "init_page()" > |
5. Добавляем два div-элемента в которых будет проигрываться входящий и исходящий видеопоток
1 2 | <div id = "localVideo" class= "display" style= "width:160px;height:120px;border: solid 1px" >< /div > <div id = "remoteVideo" class= "display" style= "width:640px;height:480px;border: solid 1px" >< /div > |
Добавляем поле для ввода SIP номера вызываемого абонента
1 | <input id = "callee" type = "text" placeholder= "Callee SIP username" /> |
6. Добавляем кнопку «Call» для совершения исходящего SIP вызова
1 | <button type = "button" onclick= "call()" >Call< /button > |
7. Добавляем div-элемент для сообщения о входящем звонке
1 | <div id = "status" >< /div > |
8. Добавляем кнопку для ответа на входящий звонок и кнопку завершения вызова
1 2 | <button id = "answerBtn" type = "button" >Answer< /button > <button id = "hangupBtn" type = "button" >Hangup< /button > |
Полный код HTML — страницы выглядит так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <!DOCTYPE html> <html lang= "en" > < head > <meta charset= "utf-8" > <script type = "text/javascript" src= "https://flashphoner.com/downloads/builds/flashphoner_client/wcs_api-2.0/current/flashphoner.js" >< /script > <script type = "text/javascript" src= "phone-video-min.js" >< /script > <style> .display { width: 100%; height: 100%; display: inline-block; } .display > video, object { width: 100%; height: 100%; } < /style > < /head > <body onload= "init_page()" > <div id = "localVideo" class= "display" style= "width:160px;height:120px;border: solid 1px" >< /div > <br> <div id = "remoteVideo" class= "display" style= "width:640px;height:480px;border: solid 1px" >< /div > <br> <input id = "callee" type = "text" placeholder= "Callee SIP username" /> <button type = "button" onclick= "call()" >Call< /button > <br> <div id = "status" >< /div > <button id = "answerBtn" type = "button" >Answer< /button > <button id = "hangupBtn" type = "button" >Hangup< /button > < /body > < /html > |
JavaScript
1. Создаем константы для статуса работы WCS и SIP сервера
1 2 | var SESSION_STATUS = Flashphoner.constants.SESSION_STATUS; var CALL_STATUS = Flashphoner.constants.CALL_STATUS; |
2. Создаем глобальные переменные для аудио потока и текущего звонка
1 2 3 | var localVideo; var remoteVideo; var currentCall; |
3. При загрузке HTML страницы инициализируем API, получаем div-элементы для проигрывания входящего и исходящего видеопотоков и вызываем функцию «connect()», которая обеспечивает подключение к WCS и SIP серверу и ожидание входящего звонка.
1 2 3 4 5 6 | function init_page() { Flashphoner.init({}); localVideo = document.getElementById( "localVideo" ); remoteVideo = document.getElementById( "remoteVideo" ); connect(); } |
4. В функции «connect()» объявляем переменные для параметров подключения к WCS и SIP серверам. Для корректной работы вам следует заменить значения на свои. URL — адрес вашего WCS, sipOptions — данные для подключения к вашему SIP серверу. После объявления переменных, функция запускает соединение с WCS и SIP серверами
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | function connect() { var url = "wss://demo.flashphoner.com:8443" var registerRequired = true ; var sipOptions = { login: "10001" , authenticationName: "10001" , password: "Pass123" , domain: "your_sip_server.com" , outboundProxy: "your_sip_server.com" , port: "5060" , registerRequired: registerRequired }; var connectionOptions = { urlServer: url, sipOptions: sipOptions }; //create session console.log( "Create new session with url " + url); Flashphoner.createSession(connectionOptions).on(SESSION_STATUS.ESTABLISHED, function (session) { console.log(SESSION_STATUS.ESTABLISHED); }).on(SESSION_STATUS.REGISTERED, function (session) { console.log(SESSION_STATUS.REGISTERED); }).on(SESSION_STATUS.INCOMING_CALL, function (call) { call.on(CALL_STATUS.RING, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.RING); }).on(CALL_STATUS.ESTABLISHED, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.ESTABLISHED); }).on(CALL_STATUS.FINISH, function () { document.getElementById( "status" ).textContent = ( " " ); console.log(CALL_STATUS.FINISH); currentCall = null; }); onIncomingCall(call); }); } |
5. Функция «call()» обеспечивает работу исходящего звонка.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | function call() { var session = Flashphoner.getSessions()[0]; var constraints = getConstraints(); var callee = document.getElementById( "callee" ).value; var outCall = session.createCall({ callee: callee, remoteVideoDisplay: remoteVideo, localVideoDisplay: localVideo, constraints: constraints, stripCodecs: "SILK" }); outCall.call(); currentCall = outCall; hangupBtn.onclick = function () { outCall.hangup(); currentCall = null; } } |
6. Функция «onIncomingCall(inCall)» обеспечивает прием входящего звонка
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function onIncomingCall(inCall) { currentCall = inCall; var constraints = getConstraints(); answerBtn.onclick = function () { inCall.answer({ localVideoDisplay: localVideo, remoteVideoDisplay: remoteVideo, constraints: constraints, stripCodecs: "SILK" }); }; hangupBtn.onclick = function () { inCall.hangup(); currentCall = null; } } |
7. Функция «getConstraints()» задает параметры потока. В этом примере браузерный SIP телефон с поддержкой видеозвонка, поэтому для параметров «audio» и «video» указываем значение «true»
1 2 3 4 5 6 7 | function getConstraints() { var constraints = { audio: true , video: true , }; return constraints; } |
Полный код JavaScript выглядит так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | var SESSION_STATUS = Flashphoner.constants.SESSION_STATUS; var CALL_STATUS = Flashphoner.constants.CALL_STATUS; var localVideo; var remoteVideo; var currentCall; function init_page() { Flashphoner.init({}); localVideo = document.getElementById( "localVideo" ); remoteVideo = document.getElementById( "remoteVideo" ); connect(); } function connect() { var url = "wss://demo.flashphoner.com:8443" var registerRequired = true ; var sipOptions = { login: "10001" , authenticationName: "10001" , password: "Pass123" , domain: "your_sip_server.com" , outboundProxy: "your_sip_server.com" , port: "5060" , registerRequired: registerRequired }; var connectionOptions = { urlServer: url, sipOptions: sipOptions }; //create session console.log( "Create new session with url " + url); Flashphoner.createSession(connectionOptions).on(SESSION_STATUS.ESTABLISHED, function (session) { console.log(SESSION_STATUS.ESTABLISHED); }).on(SESSION_STATUS.REGISTERED, function (session) { console.log(SESSION_STATUS.REGISTERED); }).on(SESSION_STATUS.INCOMING_CALL, function (call) { call.on(CALL_STATUS.RING, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.RING); }).on(CALL_STATUS.ESTABLISHED, function () { document.getElementById( "status" ).textContent = (CALL_STATUS.ESTABLISHED); }).on(CALL_STATUS.FINISH, function () { document.getElementById( "status" ).textContent = ( " " ); console.log(CALL_STATUS.FINISH); currentCall = null; }); onIncomingCall(call); }); } function call() { var session = Flashphoner.getSessions()[0]; var constraints = getConstraints(); var callee = document.getElementById( "callee" ).value; var outCall = session.createCall({ callee: callee, remoteVideoDisplay: remoteVideo, localVideoDisplay: localVideo, constraints: constraints, stripCodecs: "SILK" }); outCall.call(); currentCall = outCall; hangupBtn.onclick = function () { outCall.hangup(); currentCall = null; } } function onIncomingCall(inCall) { currentCall = inCall; var constraints = getConstraints(); answerBtn.onclick = function () { inCall.answer({ localVideoDisplay: localVideo, remoteVideoDisplay: remoteVideo, constraints: constraints, stripCodecs: "SILK" }); }; hangupBtn.onclick = function () { inCall.hangup(); currentCall = null; } } function getConstraints() { var constraints = { audio: true , video: true , }; return constraints; } |
Вид SIP телефона при входящем видеозвонке. На скриншоте ниже входящий звонок уже принят и начался обмен видеопотоками
Таким образом вы можете внедрить в свою web-страницу SIP телефон с поддержкой или без поддержки видеозвонка.
Загрузить Web Call Server 5
Системные требования: Linux x86_64, 1 core CPU, 2 Gb RAM, Java
Установка:
- wget https://flashphoner.com/download-wcs5.2-server.tar.gz
- Распаковать и установить с помощью скрипта 'install.sh'
- Запустить сервер с помощью команды 'service webcallserver start'
- Открыть веб-интерфейс https://host:8444 и активировать вашу лицензию
Если вы используете серверы Amazon EC2, то скачивать ничего не нужно.