jssip音視頻及短信開發demo(中文註釋完整版)

完整案例demo下載地址:http://download.csdn.net/download/qq_39421580/10214712

 

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="bootstrap-3.3.7/dist/css/bootstrap.css">
<link rel="stylesheet" href="toastr/toastr.min.css">
<link rel="stylesheet" href="css/me.css">
<script src="jsSip/jssip.js"></script>
<script src="jquery/jquery-1.11.3.js"></script>
<script src="toastr/toastr.min.js"></script>
<script src="js/me.js"></script>
<title>音視頻及短信jssip</title>
</head>

<body>
<div class="demo_0">
<!--註冊登陸面板start-->
<div class="demo_1" style="display:block">
<span class="font_vta">Vtalk_</span>
<input id='me_uri' class="me_uri" type="text" placeholder="請輸入您的uri地址:">
<input id='you_uri' class="you_uri" style="display:none;" type="text" placeholder="請輸入對方的uri地址:">
<!--<input class="you_uri_call" style="display:none;" type="text" placeholder="請輸入對方通話號碼">-->
<div class="device_module">
<span class="device_M" style="display:none" title="短信">M</span>
<span class="device_V" style="display:none" title="視頻">V</span>
<span class="device_C" style="display:none" title="語音">C</span>
</div>
<!--點擊C顯示通話圖標-->
<div class="device_module_call" style='display:none'>
<span class="glyphicon glyphicon-earphone callPhoneRedColor" style="display:none"></span>
<span class="glyphicon glyphicon-earphone callPhoneRedGreen" style="display:none"></span>
</div>
<button id="me_next_step" class="me_next_step">下一步</button>
<!--<button id="me_last_step" class="me_last_step" style="display:none">上一步</button>-->
</div>
<!--註冊登陸面板end-->
<!--點擊M發短信面板start-->
<div id="chatbox_message" style="display:none;">
<div id="deaderMessages" class="button">
短信消息
<span class="deaderMessages_symbol">X</span>
</div>
<div id="messages"></div>
<input id="chatinput" type="text" placeholder="請按Enter鍵發送消息:">
<button id="chatbutton">發送</button>
</div>
<!--點擊M發短信面板end-->
<!--點擊V視頻面板start-->
<div id="chatbox_video" style="display:none;">
<div id="deaderMessages_video" class="button">
正在與<span id='youVideoIng'></span>視頻通話中...
<span class="deaderMessages_symbol_video">X</span>
</div>
<div id="messages_video"></div>
<!--右側視頻專區-->
<div class="videoPrefecture_video">
<video id="youVideo" class="oneVideo"></video>
<video id="meVideo" class="twoVideo"></video>
<span class="glyphicon glyphicon-volume-down"></span>
<span class="glyphicon glyphicon-off"></span>
</div>

<input id="chatinput_video" type="text" placeholder="請按Enter鍵發送消息:">
<button id="chatbutton_video">發送</button>
</div>
<!--點擊V視頻面板end-->
</div>

</body>
</html>
 
如下是js部分:
 
$(function () {
var outgoingSession = null;
var incomingSession = null;
var currentSession = null;
// 右側視頻區start
var meVideo = document.getElementById('meVideo');
meVideo.setAttribute('autoplay', '');
meVideo.setAttribute('playsinline', '');
meVideo.style.width = '212px';

var youVideo = document.getElementById('youVideo');
youVideo.setAttribute('autoplay', '');
youVideo.setAttribute('playsinline', '');
youVideo.style.width = '531px';

var constraints = {
audio: true,
video: {
faceMode: 'user'
}
};

var localStream = null;
var userAgent = null;

navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
meVideo.srcObject = stream;
document.body.addEventListener('click', function () {
meVideo.play();
});
// 等到視頻流準備好了
var interval = setInterval(function () {
if (!meVideo.videoWidth) {
return;
}
//stage.appendChild(videoView);
clearInterval(interval);
}, 1000 / 50);
}).catch(function (error) {
onError({
name: error.name,
message: error.message
});
});
//右側視頻區end

//短信息發送
function addToChat(msg, data) {
var messages = document.getElementById('messages');
if (msg == '') {
return;
} else {
msg = sanitize(msg);
if (data == undefined) {
msg = '<strong style="position: absolute;right: 15px;">' + msg + '<img src="images/me.png" style="width:20px;">' + '</strong>';
} else {
msg = '<span style="position: absolute;left: 15px;">' + '<img src="images/you.png"style="width:20px;">' + msg + '</span>';
}
messages.innerHTML = messages.innerHTML + msg + '<br>';
messages.scrollTop = 10000;
}
 
}
//視頻短信
function addToChatVideo(msg, data) {
var messages = document.getElementById('messages_video');
if (msg == '') {
return;
} else {
msg = sanitize(msg);
if (data == undefined) {
msg = '<strong style="position: absolute;right: 15px;">' + msg + '<img src="images/me.png"style="width:20px;">' + '</strong>';
} else {
msg = '<span style="position: absolute;left: 15px;">' + '<img src="images/you.png"style="width:20px;">' + msg + '</span>';
}
messages.innerHTML = messages.innerHTML + msg + '<br>';
messages.scrollTop = 10000;
}

}

function sanitize(msg) {
return msg.replace(/</g, '&lt;');
}

//點擊下一步
$('#me_next_step').on('click', function () {
// 進行驗證
var me_uri = $('#me_uri').val();
if (me_uri == '') {
toastr.warning('請輸入您的電話號碼!');
return;
} else if (specialVerificationName(me_uri)) {
toastr.warning('輸入號碼不能有特殊字符,請輸入正確的號碼!');
return;
} else if (me_uri < 1000) {
toastr.warning('號碼不能小於1000,請從新輸入!');
$('#me_uri').val(null)
return;
} else {
// 點擊下一步驗證本身的號碼是否存在或者註冊
var me_uri = document.getElementById("me_uri").value.toString();
$.ajax({
url: "http://172.16.250.131:8080/freeswitch/myPhoneNum",
type: "GET",
dataType: "jsonp",
data: {
result: me_uri
},
success: function (data) {
console.log(data)
if (data.result == "userOnline") {
toastr.warning('用戶正在被使用,請使用其餘號碼!');
return;
} else {

$('.me_uri').css('display', 'none')
$('.you_uri').css('display', 'block')
$('.device_M').css('display', 'block')
$('.device_V').css('display', 'block')
$('.device_C').css('display', 'block')
$('.me_last_step').css('display', 'block')
$('#me_next_step').css('display', 'none')
// 進行號碼登陸註冊
var me_uri = document.getElementById("me_uri").value.toString();
var me_uri_joint = 'sip:' + me_uri + '@172.16.250.131:5060'
var ws_uri = 'ws://172.16.250.131:5066'
// 建立websocket
var socket = new JsSIP.WebSocketInterface(ws_uri);
// 配置參數
var configuration = {
sockets: [socket],
outbound_proxy_set: ws_uri,
uri: me_uri_joint,
password: '5678',
register: true, //指示JsSIP用戶代理是否應在啓動時自動註冊
session_timers: false //啓用會話定時器,默認值是true。
};
// 配置建立user agent
userAgent = new JsSIP.UA(configuration);
//成功註冊成功
userAgent.on('registered', function (data) {
console.info("registered: ", data.response.status_code, ",", data.response.reason_phrase);
});
//因爲註冊失敗而被解僱
userAgent.on('registrationFailed', function (data) {
console.log("registrationFailed, ", data);
});
// 在註冊期間發射幾秒鐘,若是應用程序沒有爲這個事件設置任何監聽器,JsSIP將像往常同樣從新註冊。
userAgent.on('registrationExpiring', function () {
console.warn("registrationExpiring");
});

//爲傳入或傳出的會話/呼叫。
userAgent.on('newRTCSession', function (data) {
console.info('onNewRTCSession: ', data);
if (data.originator == 'remote') {
console.info("incomingSession, answer the call");
incomingSession = data.session;
data.session.answer({ 'mediaConstraints': constraints, 'mediaStream': null });
if (constraints.video == false) {
//對方打入,顯示接聽電話按鈕
$('.device_module').css('display', 'none')
$('.device_module_call').css('display', 'block')
$('.callPhoneRedColor').css('display', 'block')
$('.callPhoneRedGreen').css('display', 'block')
$('.callPhoneRedGreen').css('opacity', 0.5)
var youCallSlice = data.request.headers.From['0'].raw;
youCallSlice = youCallSlice.substring(youCallSlice.indexOf('sip:'), youCallSlice.indexOf('@'));
youCallSlice = youCallSlice.replace('sip:', '')
$('#you_uri').val(youCallSlice)
constraints = {
audio: true,
video: {
faceMode: 'user'
}
};
} else {

var youCallSlice = data.request.headers.From['0'].raw;
youCallSlice = youCallSlice.substring(youCallSlice.indexOf('sip:'), youCallSlice.indexOf('@'));
youCallSlice = youCallSlice.replace('sip:', '')
$('#youVideoIng').text(youCallSlice)
$('#you_uri').val(youCallSlice)
$('.demo_1').css('display', 'none')
$('#chatbox_video').css('display', 'block')
}
} else {
var youCallSlice = $('#you_uri').val();
$('#youVideoIng').text(youCallSlice)
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) {



// alert(1)
currentSession = incomingSession;
incomingSession = null;
console.info("setCurrentSession - ", currentSession);
}
});

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);
});

data.session.on('progress', function (data) {
console.info('onProgress - ', data.originator);
if (data.originator == 'remote') {
console.info('onProgress, response - ', data.response);
}
});

data.session.on('peerconnection', function (data) {
console.info('onPeerconnection - ', data.peerconnection);
data.peerconnection.onaddstream = function (ev) {
console.info('onaddstream from remote - ', ev);
youVideo.srcObject = ev.stream;

document.body.addEventListener('click', function () {
meVideo.play();
});
// 等到視頻流準備好了
var interval = setInterval(function () {
if (!meVideo.videoWidth) {
return;
}
//stage.appendChild(videoView);
clearInterval(interval);
}, 1000 / 50);

};
});

});
//新消息
//爲傳入或傳出的MESSAGE請求而開火。
userAgent.on('newMessage', function (data) {
if (data.originator == 'local') {

console.info('onNewMessage , OutgoingRequest - ', data.request);
} else {
console.info('onNewMessage , IncomingRequest - ', data.request);
if (data.message.content != undefined) {
//短信
addToChat(data.message.content,data)
//短信和視頻
addToChatVideo(data.message.content,data)

} else {
//短信
addToChat(data.request.body,data)
//短信和視頻
addToChatVideo(data.request.body,data)
}
 
}
});

console.info("call register");
/**
* 鏈接到信令服務器,若是是以前中止則恢復到中止以前的狀態,若是是刷新操做‘’
* 並且configuration的register參數設置爲true則直接註冊到信令服務器
*/
userAgent.start();

}
},
error: function (err) {
toastr.error('鏈接失敗!')
}
});
}

//點擊視頻左邊短信進行一對一發送消息
//發送即時消息
var contentType = "text/plain";
var text = document.getElementById("chatinput_video");
// 消息發送sendMessage()
text.addEventListener('keydown', function (event) {
var you_uri = document.getElementById("you_uri").value.toString();
var you_uri_joint = 'sip:' + you_uri + '@172.16.250.131:5060';
var key = event.which || event.keyCode;
if (key === 13) {
var options = {
'eventHandlers': eventHandlers
};
userAgent.sendMessage(you_uri_joint, text.value, options);
addToChatVideo(text.value);
text.value = "";
}
}, false);
//點擊發送功能
$('#chatbutton_video').on('click', function () {
var you_uri = document.getElementById("you_uri").value.toString();
var you_uri_joint = 'sip:' + you_uri + '@172.16.250.131:5060';
var options = {
'eventHandlers': eventHandlers
};
userAgent.sendMessage(you_uri_joint, text.value, options);
addToChatVideo(text.value);
text.value = "";
})

//左側短信發送功能end


// 點擊靜音按鈕
$('.glyphicon-volume-down').on('click',function(){
var options = {
audio:true
}
userAgent.mute(options)
})

})

// 註冊監聽事件監聽各個鏈接狀態
var eventHandlers = {
'progress': function (e) {
console.log('call is in progress');
},
'failed': function (e) {
console.log('call failed: ', e);
alert('呼叫失敗');
},
'ended': function (e) {
console.log('call ended : ', e);
$('#chatbox_video').css('display', 'none');
$('.demo_1').css('display', 'block');
toastr.warning('已掛斷!');
},
'confirmed': function (e) {
console.log('call confirmed' + 'yunfei');
},
'succeeded': function (e) { // Your code here
console.log('發送成功!')
},
'failed': function (e) { // Your code here
console.log('發送失敗!')
}
};

//點擊M發短信
$('.device_M').on('click', function () {
//點擊M進行驗證查詢
var you_uri = $('#you_uri').val();
var me_uri = $('#me_uri').val();
if (you_uri == '') {
toastr.warning('請輸入對方電話號碼!');
return;
} else if (you_uri < 1000) {
toastr.warning('號碼不能小於1000,請從新輸入!');
$('#you_uri').val(null)
return;
} else if (specialVerificationName(you_uri)) {
toastr.warning('輸入號碼不能有特殊字符,請輸入正確的號碼!');
return;
} else if (you_uri == me_uri) {
toastr.warning('不能輸入本身的電話號碼!');
return;
} else {
var you_uri = document.getElementById("you_uri").value.toString();
$.ajax({
url: "http://172.16.250.131:8080/freeswitch/youPhoneNum",
type: "GET",
dataType: "jsonp",
data: {
result: you_uri
},
success: function (data) {
console.log(data)
if (data.result == "userNotOnline") {
toastr.warning('用戶不在線');
return;
} else if (data.result == "userNotExist") {
toastr.warning('用戶不存在');
return;
} else if (data.result == "busy") {
toastr.warning('用戶正在通話中...');

return;
} else {

$('.demo_1').css('display', 'none');
$('#chatbox_message').css('display', 'block');
//發送即時消息
var contentType = "text/plain";
var text = document.getElementById("chatinput");
// 消息發送sendMessage()
text.addEventListener('keydown', function (event) {
var you_uri = document.getElementById("you_uri").value.toString();
var you_uri_joint = 'sip:' + you_uri + '@172.16.250.131:5060';
var key = event.which || event.keyCode;
if (key === 13) {
var options = {
'eventHandlers': eventHandlers
};
userAgent.sendMessage(you_uri_joint, text.value, options);
addToChat(text.value);
text.value = "";
}
}, false);
//點擊發送功能
$('#chatbutton').on('click', function () {
var you_uri = document.getElementById("you_uri").value.toString();
var you_uri_joint = 'sip:' + you_uri + '@172.16.250.131:5060';
var options = {
'eventHandlers': eventHandlers
};
userAgent.sendMessage(you_uri_joint, text.value, options);
addToChat(text.value);
text.value = "";
})

}
},
error: function () {
toastr.error('鏈接失敗!')
}
})
}



})
//點擊短信關閉按鈕返回頁面
$('.deaderMessages_symbol').on('click', function () {
$('.demo_1').css('display', 'block');
$('#chatbox_message').css('display', 'none');
var me_uri = document.getElementById("me_uri").value.toString();
$.ajax({
url: 'http://172.16.250.131:8080/freeswitch/killCallByNum?command=' + me_uri,
type: "post",
dataType: 'jsonp'
});
$('#messages_video').text('');
$('#messages').text('');
})

//點擊V視頻


$('.device_V').on('click', function () {
//點擊V進行驗證查詢
var you_uri = $('#you_uri').val();
var me_uri = $('#me_uri').val();
if (you_uri == '') {
toastr.warning('請輸入對方電話號碼!');
return;
} else if (you_uri == me_uri) {
toastr.warning('不能輸入本身的電話號碼!');
return;
} else if (you_uri < 1000) {
toastr.warning('號碼不能小於1000,請從新輸入!');
$('#you_uri').val(null)
return;
} else if (specialVerificationName(you_uri)) {
toastr.warning('輸入號碼不能有特殊字符,請輸入正確的號碼!');
return;
} else {

var you_uri = document.getElementById("you_uri").value.toString();
$.ajax({
url: "http://172.16.250.131:8080/freeswitch/youPhoneNum",
type: "GET",
dataType: "jsonp",
data: {
result: you_uri
},
success: function (data) {
if (data.result == "userNotOnline") {
toastr.warning('用戶不在線');
return;
} else if (data.result == "userNotExist") {
toastr.warning('用戶不存在');
return;
} else if (data.result == "busy") {
toastr.warning('用戶正在通話中...');
return;
} else {

$('.demo_1').css('display', 'none');
$('#chatbox_video').css('display', 'block');
//左側短信發送功能start



//右側視頻功能start

//視頻
var you_uri = document.getElementById("you_uri").value.toString();
var you_uri_joint = 'sip:' + you_uri + '@172.16.250.131:5060';
/**
* 撥打參數配置,eventHandlers是註冊事件監聽的回調;mediaConstraints
* 是多媒體配置,詳細配置能夠參考:https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia;
* pcConfig能夠配置ICE服務器地址,適用於須要穿透的網絡環境
*/
var options = {
'eventHandlers': eventHandlers,
'mediaConstraints': constraints,
'mediaStream': null,
};
// 撥打音視頻電話給'sip:bob@example.com'
outgoingSession = userAgent.call(you_uri_joint, options);
//右側視頻功能end

}
},
error: function () {
toastr.error('鏈接失敗!')
}
})
}
})


//點擊短信與視頻通話關閉按鈕返回頁面
$('.deaderMessages_symbol_video').on('click', function () {
$('.demo_1').css('display', 'block');
$('#chatbox_video').css('display', 'none');
var me_uri = document.getElementById("me_uri").value.toString();
$.ajax({
url: 'http://172.16.250.131:8080/freeswitch/killCallByNum?command=' + me_uri,
type: "post",
dataType: 'jsonp'
});
$('#messages_video').text('');
$('#messages').text('');
})
//點擊C通話
$('.device_C').on('click', function () {
var you_uri = $('#you_uri').val();
var me_uri = $('#me_uri').val();
if (you_uri == '') {
toastr.warning('請輸入對方電話號碼!');
return;
} else if (you_uri == me_uri) {
toastr.warning('不能輸入本身的電話號碼!');
return;
} else if (you_uri < 1000) {
toastr.warning('號碼不能小於1000,請從新輸入!');
$('#you_uri').val(null)
return;
} else if (specialVerificationName(you_uri)) {
toastr.warning('輸入號碼不能有特殊字符,請輸入正確的號碼!');
return;
} else {
//點擊C進行驗證查詢
var you_uri = document.getElementById("you_uri").value.toString();
$.ajax({
url: "http://172.16.250.131:8080/freeswitch/youPhoneNum",
type: "GET",
dataType: "jsonp",
data: {
result: you_uri
},
success: function (data) {
if (data.result == "userNotOnline") {
toastr.warning('用戶不在線');
return;
} else if (data.result == "userNotExist") {
toastr.warning('用戶不存在');
return;
} else if (data.result == "busy") {
toastr.warning('用戶正在通話中...');
return;
} else {
var me_uri = document.getElementById("me_uri").value.toString()
$.ajax({
url: "http://172.16.250.131:8080/freeswitch/showPhoneStatus",
type: "GET",
dataType: "jsonp",
data: {
result: me_uri
},
success: function (data) {
if (data.result == "busy") {
toastr.warning('對方正在通話...')
} else {
$('.you_uri_call').css('display', 'block')
$('.device_module').css('display', 'none')
$('.me_last_step').css('display', 'none')
$('.device_module_call').css('display', 'block')
$('.callPhoneRedColor').css('display', 'block')
$('.callPhoneRedGreen').css('display', 'block')

//撥打電話隱藏接聽按鈕
$('.callPhoneRedGreen').css('opacity', 0.5)
//點擊C按鈕,撥打語音電話
var callYouUri = document.getElementById("you_uri").value.toString();
var callYouUri_joint = 'sip:' + callYouUri + '@172.16.250.131:5060';

var constraints = {
audio: true,
video: false
};


var options = {
'eventHandlers': eventHandlers,
'mediaConstraints': constraints,
'mediaStream': null
};
outgoingSession = userAgent.call(callYouUri_joint, options);

}
},
error: function (err) {
toastr.error('鏈接失敗!')
}
});

}
},
error: function () {
toastr.error('鏈接失敗!')
}
})
}
})
//點擊電話通話掛斷返回上一層
$('.callPhoneRedColor').on('click', function () {
$('.you_uri').css('display', 'block')
$('.you_uri_call').css('display', 'none')
$('.device_module').css('display', 'block')
$('.me_last_step').css('display', 'block')
$('.device_module_call').css('display', 'none')
$('.callPhoneRedColor').css('display', 'none')
$('.callPhoneRedGreen').css('display', 'none')
})

//點擊視頻掛斷
$('.glyphicon-off').on('click', function () {
var me_uri = document.getElementById("me_uri").value.toString();
$.ajax({
url: 'http://172.16.250.131:8080/freeswitch/killCallByNum?command=' + me_uri,
type: "post",
dataType: 'jsonp'
});
//點擊掛斷按鈕清空左側信息
$('#messages_video').text('');
$('#messages').text('');
$('#chatbox_video').css('display', 'none');
$('.demo_1').css('display', 'block');
})

//點擊語音進行掛斷,獲取本地輸入的uri
$('.callPhoneRedColor').on('click', function () {
var me_uri = document.getElementById("me_uri").value.toString();
$.ajax({
url: 'http://172.16.250.131:8080/freeswitch/killCallByNum?command=' + me_uri,
type: "post",
dataType: 'jsonp'
});
})
/**
* 過濾全部特殊字符串和空格
* @param s
* @returns {boolean}
*/
function specialVerificationName(s) {
var pattern = new RegExp("[`~ !@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:」「'。,、?]")
return pattern.test(s)
}

})
相關文章
相關標籤/搜索