anxiao_web/rtc/js/mvrCarVideo.js

819 lines
23 KiB
JavaScript
Raw Permalink Normal View History

2024-07-24 09:22:32 +08:00
import {timestampFormat,getParams,fullScreen,exitFullscreen} from "./timestampFormat.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*30;
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("title"));
var loginUserName=decodeURI(getParams("username"));
var power=decodeURI(getParams("power"));
var videoId="";//给解图使用
var screenshotFlag=0;
var rtmName=channelValue;
var rtmClient=null;
var rtmChannel;
var uid=(new Date().getTime())+channelValue;
var client=null;
var localStream=null;
var stream=null;//远端流
var buffer=[];
var mediaRecorder =null;
$("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(){
// rtmChannel.leave();//我先离开频道
// var obj=getRtmData("videoclose","");//在去关闭
// sendMainChannelMessage(obj);
// window.close();
}
//关闭并退出
$(".videoNav>.nav>img:nth-child(1)").click(function(){
closePage();
var param = {
"sender":"children",
"receiver":"parent",
"deviceid":channelValue,
"cmd":"closePage"
};
window.parent.postMessage(param,'*');
})
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();
}
}
//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;;
}
setPageSize(x,y,width,height)
}
//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 video").css("width",width+"px");
$("#video video").css("height",height+"px");
$("#video video").css("left",x);
$("#video video").css("top",y);
}
$(".videoFullscreen").click(function(){
var url=window.location.href;
if(url.indexOf("alarmDeviceVideo")!=-1){
//投一个新的屏幕出去
var width=1280;
var height=760;
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");
}else{
var model=$(this).attr("model");
if(model=="exitfullScreen"){
fullScreen()
var w=parseFloat(window.screen.width );
var h=parseFloat(window.screen.height -40);
if(sizeLevel==1){
setVideoSize1280(w,h)
}else{
setVideoSize640(w,h);
}
$(this).attr("src","images/videoExitFullscreen.png").attr("model","fullScreen").attr("title","退出全屏")
}else{
exitFullscreen()
if(sizeLevel==1){
$("#video video").css("width","768px").css("height","432px");
}else{
$("#video video").css("width","640px").css("height","480px");
}
$("#video video").css("left",0);
$("#video video").css("top",0);
$(this).attr("src","images/videoFullscreen.png").attr("model","exitfullScreen").attr("title","全屏");
}
}
})
//打开声音
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);
}
stream.setAudioVolume(value);
}
});
}
//调节音量大小
$(".closeMute").click(function(){
var mute=$(this).attr("mute");
if(mute=="open"){
stream.setAudioVolume(0);
sliderInit.setValue(0) //设置开始值
closeMute(this);
}else{
stream.setAudioVolume(100);
sliderInit.setValue(100) //设置开始值
openMute(this);
}
})
function videoJoin() {
client = AgoraRTC.createClient({mode: 'live',codec: "h264"});
client.init(appid, function () {
client.join(appid,channelValue, null, function(uid) {
console.log("用户进入视频频道")
},function(err) {
});
},function (err) {
});
client.on('stream-added', function (evt) {//监听 "stream-added" 事件,当有远端流加入时订阅该流。
var stream = evt.stream;
stream.setAudioVolume(0);
client.subscribe(stream, function (err) {
});
setInterval(()=>{
client.getRemoteVideoStats((evt)=>{
if(JSON.stringify(evt)!="{}"){
for(var j in evt){
var PacketLossRate=evt[j]["PacketLossRate"]
var RecvBitrate=evt[j]["RecvBitrate"]
var RenderFrameRate=evt[j]["RenderFrameRate"]
var TotalPlayDuration=evt[j]["TotalPlayDuration"]
var TotalFreezeTime=evt[j]["TotalFreezeTime"]
var TransportDelay=evt[j]["TransportDelay"]
$(".PacketLossRate").html(PacketLossRate);
$(".RecvBitrate").html(RecvBitrate);
$(".RenderFrameRate").html(RenderFrameRate);
$(".TotalPlayDuration").html(TotalPlayDuration);
$(".TotalFreezeTime").html(TotalFreezeTime);
$(".TransportDelay").html(TransportDelay);
}
}
})
},1000)
var timer=setInterval(() => {
client.getRemoteVideoStats((evt)=>{
if(JSON.stringify(evt)!="{}"){
for(var i in evt){
if("RecvResolutionHeight" in evt[i]){
var RecvResolutionHeight=evt[i]["RecvResolutionHeight"];
}
if("RecvResolutionWidth" in evt[i]){
var RecvResolutionWidth=evt[i]["RecvResolutionWidth"];
}
if((RecvResolutionWidth!="0"&&RecvResolutionHeight!="0")&&(RecvResolutionWidth!=undefined&&RecvResolutionHeight!=undefined)){
clearInterval(timer);
var width=RecvResolutionWidth;
var height=parseFloat(RecvResolutionHeight);
if(RecvResolutionWidth=="1280"&&RecvResolutionHeight=="720"){
sizeLevel=1;
width=RecvResolutionWidth*0.6;
height=RecvResolutionHeight*0.6;
$("#video video").css("width","768px").css("height","432px");
}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("496","750");
}else if(RecvResolutionWidth=="640"&&RecvResolutionHeight=="480"){
sizeLevel=4;
$("#video video").css("width","640px").css("height","480px");
//window.resizeTo(RecvResolutionWidth,RecvResolutionHeight);
}
// var param={
// "deviceid":channelValue,
// "cmd":"videoloadedSuccess"
// }
// parent.postMessage(param,'*');
// //启动倒计时
// downTime30();
}
}
}
})
},100)
});
client.on('stream-subscribed', function (evt) {//监听 "stream-subscribed" 事件,订阅成功后播放远端流。
stream = evt.stream;
stream.resume();
var children=$("#video").children().siblings("#agora_local");
var length=children.length;
videoId=stream.getId();
window.stream=stream.stream;
$("#video .resetPlay").empty();
if (length === 0) {
$('#video').append('<div id="agora_remote'+stream.getId()+'" style="float:left; width:100%;height:100%;display:inline-block;"></div>');
}else{
$('#video').append('<div id="agora_remote'+stream.getId()+'" style="float:left;width:100%;height:100%;display:inline-block;"></div>');
}
stream.play('agora_remote' + stream.getId());
setVideoWidth();
videoSlideInit();
});
client.on('stream-removed', function (evt) {//当远端流被移除时(例如远端用户调用了 Stream.unpublish 停止播放该流并移除它的画面。
var stream = evt.stream;
stream.stop();
$('#agora_remote' + stream.getId()).remove();
var name="视频加载中,请稍候..."
reserPlay(name);
setVideoWidth();
});
client.on("client-banned",function (evt) {
closePage();
})
client.on('peer-leave', function (evt) {//调用 Client.leave 方法离开频道。
var stream = evt.stream;
if (stream) {
stream.stop();
$('#agora_remote' + stream.getId()).remove();
var name="用户已退出,请重连..."
reserPlay(name);
}
setVideoWidth();
});
}
//开启远程录像
$(".startRecording").unbind();
$(".startRecording").click(function(){
var recordState=$(this).attr("state");
if(recordState=="open"){
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");
}
})
//开启对讲
$(".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;
}else{
applyPage=false;
bApplySign=false;
//关闭
$(this).attr("state","close");
$(this).attr("src","images/videoWalk.png");
}
})
//键盘松开
document.onkeyup = function (event) {
var e = event || window.event || arguments.callee.caller.arguments[0];
if(applyPage){
if(e && e.keyCode == keyCode&&!bApplySign) {
bApplySign = true;
setTimeout(()=>{
//开始发言
client.unpublish(localStream, function(err) {
console.log("关闭自己的流")
console.log(err);
});
},500)
var select=$(".closeMute");
openMute(select);
stream.setAudioVolume(100);
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) {
console.log("键盘按下")
bApplySign = false;
localStream = AgoraRTC.createStream({streamID: uid, audio: true, video:false});
localStream.setVideoProfile('360p_3');
localStream.init(function() {
localStream.play('agora_local');
client.publish(localStream, function (err) {
console.log("Publish local stream error: " + err);
});
stream.setAudioVolume(0);
sliderInit.setValue(0) //设置开始值
var select=$(".closeMute");
closeMute(select);
}, function (err) {
console.log("getUserMedia failed", err);
});
}
}
}
//截图,并且把图片保存在云端
$(".videoImg").click(function(){
var video=document.getElementById("video"+videoId);
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") ;
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--;
if(closeTime<=0){
closeVideoStream();//发送关闭指令
leaveChannel();//离开频道
clearInterval(closePageTimer);//退出定时器
}else{
$(".close_ing_time").html(closeTime);
}
},1000);
}
function videoTitleEvent(){
$(".videoTitle>p:last-child>button:nth-child(1)").on('click',function(){
$(".videoTitle").css("display","none");
clearInterval(closePageTimer);
closePageTimer=null;
closeTime=10;
cdTimeCount=videoTime;
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){
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){
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","");
console.log(obj);
sendMainChannelMessage(obj);
//每隔1分钟发送发送1个不关闭视频的指令
},5000)
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);
}
})
}
}