anxiao_web/rtc/js/deviceAlarmVideo.js

906 lines
24 KiB
JavaScript
Raw Normal View History

2024-07-24 09:22:32 +08:00
import {timestampFormat,getParams,fullScreen,exitFullscreen} from "./timestampFormat.js";
import { mqttUrl } from "../../public/js/url.js";
window.onload=function(){
var locationUrl=window.location.href;
var appid="78846e9910a846688ab959e0f87034e5";//声网
var slider,sliderInit,layer;
layui.use(['slider','layer'], function(){
slider= layui.slider;
layer = layui.layer;
});
var sizeLevel=0;//放大等级
var videotapeStartTime="";//录像开始时间
var videotapeEndTime="";//录像结束时间
var startTimeStamp="";
var endTimeStamp="";
var bApplySign = false;
var applyPage=false;
var keyCode = 32;
var videoTime=60000*10;
var cdTimeCountFlag="video";//video跟videotape
var cdTimeCount=videoTime;
var countDownTimer=null;
var channelValue=decodeURI(getParams("id"));
var mdDeviceName=decodeURI(getParams("mdDeviceName"));
var station=decodeURI(getParams("station"));
var title=decodeURI(getParams("mdDeviceName"));
var loginUserName=decodeURI(getParams("username"));
var power=decodeURI(getParams("power"));
var screenshotFlag=0;
var rtmName=channelValue;
var rtmClient=null;
var rtmChannel;
var uid=(new Date().getTime())+channelValue;
var client=null;
var buffer=[];
var mediaRecorder =null;
var videoTimer=null;
var options = {
appid: "78846e9910a846688ab959e0f87034e5",
channel: channelValue,
uid: '',
token: null
};
var client=AgoraRTC.createClient({mode: 'live',codec: "vp8"});
var remoteUsers = {};
let localTracks = {
audioTrack: true
};
$("html>head>title").html(title);
videoJoin();
rtmJoin();
setPower(power);
function setPower(power){
if(power=="null"){
power=0;
}
if(power>=90){
var img="images/power100.png";
}else if(power>=70){
var img="images/power80.png";
}else if(power>=50){
var img="images/power60.png";
}else if(power>=30){
var img="images/power40.png";
}else if(power>=10){
var img="images/power20.png";
}else{
var img="images/power0.png";
}
$(".power>span").html(power+"%");
$(".power>img").attr("src",img);
}
function closePage(){
leaveChannel();//我先离开频道
var obj=getRtmData("videoclose","");//在去关闭
sendMainChannelMessage(obj);
window.close();
}
async function leaveChannel() {
// leave the channel
await client.leave();
}
//关闭并退出
$(".videoNav>.nav>img:nth-child(1)").click(function(){
var param = {
"sender":"children",
"receiver":"parent",
"deviceid":channelValue,
"cmd":"closePage"
};
window.parent.postMessage(param,'*');
closePage();
})
window.addEventListener('message', function(e) {
var data=e.data
var cmd=data["cmd"];
var deviceid=data["deviceid"]
if(cmd=="videoclose"){
if(channelValue==deviceid){
closePage();
}
}
})
//如果在全屏
function confClosePage(){
var url=window.location.href;
if(url.indexOf("fullScreenVideo")==-1){
//closePage();
}
}
$(window).unload(function () {
//防止9空格切换的时候关闭视频
if(locationUrl.indexOf("videoMoitorShow")==-1){
//confClosePage();
}
});
window.onbeforeunload=function(e){
if(locationUrl.indexOf("videoMoitorShow")==-1){
//confClosePage();
}
}
window.onresize = function () {
var w=parseFloat(window.innerWidth);
var h=parseFloat(window.innerHeight - 40);
switch(sizeLevel){
case 1:
setVideoSize1280(w,h);
break;
case 2:
setVideoSize720(w,h);
break;
case 3:
setVideoSize480(w,h);
break;
case 4:
setVideoSize640(w,h);
break;
default:
break;
}
}
//1280*720
function setVideoSize1280(w,h){
var f=parseFloat(h/w);
if(f >= 0.5625){
var width=w;
var height=width*0.5625;
var x= 0;
var y=parseFloat(h-height)/2;
}else{
var height=h;
var width=(height*16)/9;
var x=parseFloat(w-width)/2;
var y= 0;
}
setPageSize(x,y,width,height)
}
//720*1280
function setVideoSize720(w,h){
var f=parseFloat(w/h);
if(f>=0.5625){
var height=h;
var width=h*0.5625;
var x=parseFloat(w-width)/2;
var y=0;
}else{
var width=w;
var height=(w*16)/9;
var x=0;
var y=parseFloat(h-height)/2;;
}
setPageSize(x,y,width,height)
}
//480*640
function setVideoSize480(w,h){//宽度是480px;height:640px;
var f=parseFloat(w/h);
if(f>=0.75){
var height=h;
var width=h*0.75;
var x=parseFloat(w-width)/2;
var y=0;
}else{
var width=w;
var height=(w*4)/3;
var x=0;
var y=parseFloat(h-height)/2;;
}
console.log(f);
console.log(x,y,width,height);
setPageSize(0,0,120,160)
}
//640*480
function setVideoSize640(w,h){
var f=parseFloat(h/w);
if(f >= 0.75){
var width=w;
var height=width*0.75;
var x= 0;
var y=parseFloat(h-height)/2;
}else{
var height=h;
var width=(height*4)/3;
var x=parseFloat(w-width)/2;
var y= 0;
}
setPageSize(x,y,width,height)
}
function setPageSize(x,y,width,height){
$("#video").css("width",width+"px");
$("#video").css("height",height+"px");
$("#video").css("left",x);
$("#video").css("top",y);
}
$(".videoFullscreen").unbind('click');
$(".videoFullscreen").click(function(){
var url=window.location.href;
//投一个新的屏幕出去
var width=1280;
var height=720;
window.open("fullScreenVideo.html?id="+encodeURI(channelValue)+"&power="+encodeURI(power)+"&mdDeviceName="+encodeURI(encodeURI(mdDeviceName))+"&station="+encodeURI(encodeURI(station))+"&title="+encodeURI(encodeURI(title))+"&username="+loginUserName,"","width="+width+",height="+height+",top=0,left=0");
})
//打开声音
function openMute(select){
$(select).attr("src","images/openMute.png");
$(select).attr("title","音量");
$(select).attr("mute","open");
}
//关闭声音
function closeMute(select){
$(select).attr("src","images/closeMute.png");
$(select).attr("title","静音");
$(select).attr("mute","close");
}
//初始化声音
function videoSlideInit(){
sliderInit=slider.render({
elem: '#slideTest1',
change: function(value){
var select=$(".closeMute");
if(value==0){
closeMute(select);
}else{
openMute(select);
}
setRemoteUserMute(value*10);
}
});
}
function setRemoteUserMute(value){
for(var user in remoteUsers){
remoteUsers[user].audioTrack.setVolume(value);
}
}
let cameraid=0;
let rotateid=0;
//摄像图的操作
$(".carmeOper").on('click',function(){
rotateid=parseInt($(this).attr("rotate"));
$(".carmeOper").removeClass("bgColor");
$(this).addClass("bgColor")
sendCarmeOper();
})
//摄像头的方向调整
$(".carmeDir").on('click',function(){
let dir=$(this).attr("dir");
cameraid=dir;
if(dir=="0"){
$(this).attr("dir","1");
$(this).html("后");
}else{
$(this).attr("dir","0");
$(this).html("前");
}
sendCarmeOper();
})
function sendCarmeOper(){
var obj=getRtmData("videoclose","");
sendMainChannelMessage(obj);
setTimeout(()=>{
let data={
"rtmpflag":0,
"camera":cameraid,
"rotation":rotateid
}
var obj=getRtmData("videocall",JSON.stringify(data));
sendMainChannelMessage(obj);
videoInfoWind();
},4000)
}
//调节音量大小
$(".closeMute").click(function(){
var mute=$(this).attr("mute");
if(mute=="open"){
setRemoteUserMute(0)
sliderInit.setValue(0) //设置开始值
closeMute(this);
}else{
setRemoteUserMute(1000)
sliderInit.setValue(100) //设置开始值
openMute(this);
}
})
async function videoJoin() {
//订阅用户推送流
client.on("user-published", handleUserPublished);
//订阅用户取消推流
client.on("user-unpublished", handleUserUnpublished);
try {
// join a channel and create local tracks, we can use Promise.all to run them concurrently
[ options.uid] = await Promise.all([
// join the channel
client.join(options.appid, options.channel, options.token || null),
]);
} catch (e) {
console.log("加入频道失败", e);
}
// 使用 Web SDK 4.x,服务器频道禁用以后,客服端需要退出页面跟频道
client.on("connection-state-change", (curState, prevState) => {
closePage();
});
}
async function subscribe(user, mediaType) {
const uid = user.uid;
// subscribe to a remote user
await client.subscribe(user, mediaType);
if (mediaType === 'video') {
const player = $(`
<div id="player-${uid}" class="player"></div>
`);
$("#agora_local").append(player);
user.videoTrack.play(`player-${uid}`);
//设置视频数据
setVideoData();
//初始化视频的尺寸
videoInfoWind();
}
if(mediaType === 'audio'){
setRemoteUserMute(0);
//初始化音量
videoSlideInit();
user.audioTrack.play();
}
}
function handleUserPublished(user, mediaType) {
const id = user.uid;
remoteUsers[id] = user;
subscribe(user, mediaType);
}
function handleUserUnpublished(user) {
const id = user.uid;
delete remoteUsers[id];
$(`#player-wrapper-${id}`).remove();
}
function setVideoData(){
setInterval(()=>{
var evt=client.getRemoteVideoStats();
if(JSON.stringify(evt)!="{}"){
for(var j in evt){
var packetLossRate=evt[j]["packetLossRate"]
var receiveBitrate=parseFloat(evt[j]["receiveBitrate"]/1024).toFixed(2);
var receiveFrameRate=evt[j]["receiveFrameRate"]
var totalDuration=evt[j]["totalDuration"]
var totalFreezeTime=evt[j]["totalFreezeTime"]
var transportDelay=evt[j]["transportDelay"]
$(".PacketLossRate").html(packetLossRate);
$(".RecvBitrate").html(receiveBitrate);
$(".RenderFrameRate").html(receiveFrameRate);
$(".TotalPlayDuration").html(totalDuration);
$(".TotalFreezeTime").html(totalFreezeTime);
$(".TransportDelay").html(transportDelay);
}
}
},1000)
}
function videoInfoWind(){
videoTimer=setInterval(() => {
var evt=client.getRemoteVideoStats();
if(JSON.stringify(evt)!="{}"){
for(var i in evt){
if("receiveResolutionHeight" in evt[i]){
var RecvResolutionHeight=evt[i]["receiveResolutionHeight"];
}
if("receiveResolutionWidth" in evt[i]){
var RecvResolutionWidth=evt[i]["receiveResolutionWidth"];
}
if((RecvResolutionWidth!="0"&&RecvResolutionHeight!="0")&&(RecvResolutionWidth!=undefined&&RecvResolutionHeight!=undefined)){
clearInterval(videoTimer);
var width=RecvResolutionWidth;
var height=parseFloat(RecvResolutionHeight);
if(RecvResolutionWidth=="1280"&&RecvResolutionHeight=="720"){
sizeLevel=1;
}else if(RecvResolutionWidth=="720"&&RecvResolutionHeight=="1280"){
if(window.screen.height+200<=height){
width=width*0.8;
height=height*0.8;
}
sizeLevel=2;
window.resizeTo(width,height);
}else if(RecvResolutionWidth=="480"&&RecvResolutionHeight=="640"){
sizeLevel=3;
window.resizeTo("480","640");
}else if(RecvResolutionWidth=="640"&&RecvResolutionHeight=="480"){
sizeLevel=4;
window.resizeTo(RecvResolutionWidth,RecvResolutionHeight);
}
var param={
"deviceid":channelValue,
"cmd":"videoloadedSuccess",
"data":{
w:width,
h:height
}
}
console.log(param);
parent.postMessage(param,'*');
//启动倒计时
downTime30();
}
}
}
},1000)
}
//设置stream
function setRecStream(){
let mediaStream = new MediaStream();
console.log(mediaStream);
for(var user in remoteUsers){
mediaStream.addTrack(remoteUsers[user].videoTrack.getMediaStreamTrack())
mediaStream.addTrack(remoteUsers[user].audioTrack.getMediaStreamTrack())
}
window.stream=mediaStream;
}
//开启远程录像
$(".startRecording").unbind();
$(".startRecording").click(function(){
var recordState=$(this).attr("state");
if(recordState=="open"){
setRecStream();
startRecord();
startTimeStamp=new Date().getTime();
videotapeStartTime=timestampFormat();
$(this).attr("state","close");
$(this).attr("src","images/endRecording.png");
$(this).attr("title","结束录像");
layer.msg("录像开启成功");
$(".inTheVideo").css("display","block");
cdTimeCountFlag="videotape";
downTime30();
}else{
endTimeStamp=new Date().getTime();
videotapeEndTime=timestampFormat();
stopRecord();
cdTimeCount=videoTime;
clearInterval(countDownTimer);
countDownTimer=null;
cdTimeCountFlag="video";
}
})
//视频信息
$(".videoReInfo").on('click',function(){
var state=$(this).attr("state");
if(state=="close"){
$(this).attr("state","open");
$(".videoInfo").css("display","block");
}else{
$(this).attr("state","close");
$(".videoInfo").css("display","none");
}
})
//分享
$(".videoShare").on('click',function(){
var state=$(this).attr("state");
if(state=="close"){
$(this).attr("state","open");
$("#qrcode").css("display","block");
}else{
$(this).attr("state","close");
$("#qrcode").css("display","none");
}
})
async function setClientHost(){
//设置成主播
await client.setClientRole("host");
try {
// join a channel and create local tracks, we can use Promise.all to run them concurrently
[localTracks.audioTrack] = await Promise.all([
// create local tracks, using microphone and camera
AgoraRTC.createMicrophoneAudioTrack()
]);
await client.publish(Object.values(localTracks));
} catch (e) {
console.log("加入频道失败", e);
}
}
async function setClientAudience(){
//先调用取消发布,在设置成观众
await client.unpublish(Object.values(localTracks));
await client.setClientRole("audience");
}
//开启对讲
$(".videoWalk").unbind();
$(".videoWalk").click(function(){
var state=$(this).attr("state");
if(state=="close"){
//开启
$(this).attr("state","open");
$(this).attr("src","images/videoWalkOnline.png");
applyPage=true;
bApplySign=true;
setClientHost();
}else{
applyPage=false;
bApplySign=false;
//关闭
$(this).attr("state","close");
$(this).attr("src","images/videoWalk.png");
setClientAudience();
}
})
//键盘松开
document.onkeyup = function (event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if(applyPage){
if(e && e.keyCode == keyCode&&!bApplySign) {
bApplySign = true;
//关闭麦克风
localTracks.audioTrack.setEnabled(false);
//开启远程的声音
setRemoteUserMute(100);
var select=$(".closeMute");
openMute(select);
sliderInit.setValue(100) //设置开始值
}
}
}
//键盘按下
document.onkeydown = function (event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if(applyPage){
if(e && e.keyCode == keyCode&&bApplySign) {
bApplySign = false;
//启用麦克风
localTracks.audioTrack.setEnabled(true);
//关闭远程的声音
setRemoteUserMute(0);
//页面状态改变
sliderInit.setValue(0) //设置开始值
var select=$(".closeMute");
closeMute(select);
}
}
}
//截图,并且把图片保存在云端
$(".videoImg").click(function(){
var video=document.querySelector(".agora_video_player");
var canvas=document.getElementById('canvas');
if(video!=null){
$(".canvasImg").css("display","block");
canvas.width=video.videoWidth;
canvas.height=video.videoHeight;
canvas.getContext('2d').drawImage(video,0,0,canvas.width,canvas.height);
var image = canvas . toDataURL ("image/png") ;
$(".canvasImgBox").css("width",canvas.width*0.3+"px");
$(".canvasImgBox").css("height",canvas.height*0.3+"px");
document.getElementById("save").href=image;
document.getElementById("save").download=mdDeviceName+".jpg";
document.getElementById('save').onclick=function(){
$(".canvasImg").css("display","none");
}
document.getElementById('cancel').onclick=function(){
$(".canvasImg").css("display","none");
}
}else{
layer.msg("用户已离开,无法截图");
}
})
function closeVideoStream(){
var obj=getRtmData("videoclose","");//在去关闭
sendMainChannelMessage(obj);
}
function reserPlay(name){
$("#video").html("<p class='resetPlay'><span>"+name+"</span><img src='images/resetPlay.png'></p>");
$("#video").css("backgroundImage","none");
$("#video").css("backround","#000");
$("#video>p").on('click',function(){
closeVideoStream();
setTimeout(function(){
var obj=getRtmData("videocall","");
sendMainChannelMessage(obj);
},1500)
})
}
//倒计时30分钟以后关闭录像告诉用户,录像已经完成
/*************************观看视频为5分钟1次如果不点击确定就会关闭***********************************/
function downTime30(){
if(countDownTimer!=null){
clearInterval(countDownTimer);
}else{
countDownTimer=setInterval(function(){
cdTimeCount-=1000;
if(cdTimeCount<=0){
clearInterval(countDownTimer);
countDownTimer=null;
if(cdTimeCountFlag=="videotape"){
endTimeStamp=new Date().getTime();
videotapeEndTime=timestampFormat();
stopRecord();
}else{
//倒计时
showCountDownTimer();
}
}
},1000);
}
}
//倒计时*******************************************
var closeTime=10;//倒计时
var closePageTimer=null;
function showCountDownTimer(){
$(".videoTitle").css("display","block");
$(".close_ing_time").html(closeTime);
videoTitleEvent();
closePageTimer=setInterval(function(){
closeTime--;
$(".close_ing_time").html(closeTime);
if(closeTime<=0){
closeVideoStream();//发送关闭指令
leaveChannel();//离开频道
clearInterval(closePageTimer);//退出定时器
}
},1000);
}
function videoTitleEvent(){
$(".videoTitle>p:last-child>button:nth-child(1)").on('click',function(){
var obj=getRtmData("videocall","");//在去关闭
sendMainChannelMessage(obj);
$(".videoTitle").css("display","none");
clearInterval(closePageTimer);
closePageTimer=null;
closeTime=10;
cdTimeCount=videoTime;
//再次加入频道
videoJoin()
downTime30()
})
$(".videoTitle>p:last-child>button:nth-child(2)").on('click',function(){
closePage();
})
}
function handleDataAvailable(e){ // 5、获取数据的事件函数 当我们点击录制之后,数据就会源源不断的从这个事件函数中获取到
if(e && e.data && e.data.size > 0){
console.log(e.data);
buffer.push(e.data); // 将e.data放入二进制数组里面
// 这个buffer应该是我们在开始录制的时候创建这个buffer
}
}
//开始录像
function startRecord(){
buffer = []; // 定义数组
if (typeof MediaRecorder.isTypeSupported == 'function') {
if (MediaRecorder.isTypeSupported('video/webm;codecs=vp8')) {
var options = {
mimeType: 'video/webm;codecs=vp9,opus'
}
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=vp9')) {
var options = {
mimeType:'video/webm;codecs=vp9,opus'
};
} else if (MediaRecorder.isTypeSupported('video/webm;codecs=h264')) {
var options = {
mimeType:'video/webm;codecs=h264,opus'
};
}
}
if(!MediaRecorder.isTypeSupported(options.mimeType)){ // 判断录制的视频 mimeType 格式浏览器是否支持
return;
}
try{ // 防止录制异常
// 5、先在上面定义全局对象mediaRecorder以便于后面停止录制的时候可以用到
mediaRecorder = new MediaRecorder(window.stream, options); // 调用录制API // window.stream在gotMediaStream中获取
//4、调用事件 这个事件处理函数里面就会收到我们录制的那块数据 当我们收集到这个数据之后我们应该把它存储起来
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(10); // start方法里面传入一个时间片每隔一个 时间片存储 一块数据
}catch(e){
console.error(e);
return;
}
}
//停止录制
function stopRecord(){
//6、调用停止录制
try{
mediaRecorder.stop();
}catch(e){
console.error(e);
}
$(".startRecording").attr("state","open");
$(".startRecording").attr("src","images/startRecording.png");
$(this).attr("title","开始录像");
layer.msg('录像已保存', {
time: false, //20s后自动关闭
btn: ['知道了']
});
$(".inTheVideo").css("display","none");
var tmpBlob = new Blob(buffer, {type: 'video/webm'});
var duration=endTimeStamp-startTimeStamp;
//调用设置时长代码。该函数基于fix-webm-duration.js
ysFixWebmDuration(tmpBlob, duration, function (fixedBlob) {
var recorderFile = fixedBlob;
let name =`${mdDeviceName}(${videotapeStartTime}---${videotapeEndTime}).mp4`;
var url = window.URL.createObjectURL(recorderFile);
var a = document.createElement('a');
a.href = url;
a.style.display = 'none';
a.download = name;
a.click();
});
}
function setVideoWidth(){
var children=$("#video").children().siblings("#agora_local");
for(var i=0;i<children.length;i++){
var div=children[i];
var id=$(div).attr("id");
var w=parseInt(100/(children.length))+"%";
document.getElementById(id).style.width=w;
}
}
var rtmJoinConnect=3;
function rtmJoin(){
rtmClient = AgoraRTM.createInstance(appid);
rtmClient.on('ConnectionStateChanged', (newState, reason) => {
if(newState=="RECONNECTING"){//说明连接断开了
//登出
rtmClient.logout();
var rtmJoinTimer=setInterval(()=>{
if(rtmJoinConnect>0){
rtmJoin()
rtmJoinConnect--
}else{
clearInterval(rtmJoinTimer);
}
},30000)
}
});
rtmClient.login({ token: null, uid:uid}).then(() => {
rtmJoinConnect=3;
setInterval(function(){
var obj=getRtmData("videowatching","");
sendMainChannelMessage(obj);
//每隔1分钟发送发送1个不关闭视频的指令
},60000)
rtmChannel= rtmClient.createChannel("vlive"+rtmName);//此处传入频道 ID
rtmChannel.join().then(() => {
/* 加入频道成功的处理逻辑 */
rtmChannel.on('ChannelMessage', ({ text }, senderId) => { // text 为收到的频道消息文本senderId 为发送方的 User ID
/* 收到频道消息的处理逻辑 */
console.log(text);
var deviceInfo=JSON.parse(text);
var power=deviceInfo["power"];
setPower(power);
});
}).catch(error => {
/* 加入频道失败的处理逻辑 */;
});
}).catch(err => {
console.log('AgoraRTM client login failure', err);
});
}
function sendMainChannelMessage(obj){
sendMqttData(obj);
rtmClient.sendMessageToPeer(
{ text:JSON.stringify(obj)}, // 符合 RtmMessage 接口的参数对象
rtmName, // 远端用户 ID
).then(sendResult => {
if (sendResult.hasPeerReceived) {
/* 远端用户收到消息的处理逻辑 */
if(screenshotFlag==1){
layer.msg("截图成功");
}else if(screenshotFlag==2){
layer.msg("开始录像");
$(".startRecording").attr("src","images/endRecording.png").attr("state","close").attr("title","结束录像")
}else if(screenshotFlag==3){
layer.msg("停止录像");
$(".startRecording").attr("src","images/startRecording.png").attr("state","open").attr("title","停止录像")
}
screenshotFlag=0;
} else {
if(screenshotFlag==1){
layer.msg("截图失败,设备不再线");
}
}
})
}
//构建rtm发送对象
function getRtmData(title,data){
return {
"title":title,
"sender":loginUserName,
"department":"",
"scope":"",
"receiver":[rtmName],
"video":"",
"rtm":(new Date().getTime()).toString(),
"data":data,
"userScope":"",
"userBragide":"",
"userDetachchment":"",
"userBorough":"",
"name":"",
}
}
//发送mqqt接口数据
function sendMqttData(obj){
var mqttObj={
"topic":`${station}/ter_cmd`,
"message":JSON.stringify(obj)
}
$.ajax({
url: mqttUrl,
type: "post",
dataType: "json",
headers: {
"Content-Type": "application/json;charset=utf-8"
},
data: JSON.stringify(mqttObj),
success: function(d) {
//console.error(d);
}
})
}
}