播放器.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Conference Live</title>
    <link rel="stylesheet" href="./styles/iconfont.css" />
    <link rel="stylesheet" href="./styles/conferenceLive.css" />
  </head>

  <body class="conferenceLive">
    <div class="loading">
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
      <span></span>
    </div>
    <div class="canvasWrap single-screen m-single-screen">
      <canvas id="mainStream" width="750" height="413"></canvas>
      <canvas id="auxiliaryStream" width="750" height="413"></canvas>
    </div>
    <div class="controlWrap">
      <!-- 视频进度条 -->
      <div class="videoProgress">
        <input class="videoRange" type="range" value="0" min="0" max="3600" />
      </div>
      <div class="controls">
        <div class="leftControl">
          <!-- 直播——播放/停止 -->
          <div class="liveControl">
            <span
              class="livePlay iconfont icon-play-video icon-pause-video"
            ></span>
          </div>
          <!-- 录像控制 -->
          <div class="recordControl">
            <!-- 播放/暂停 -->
            <span class="iconfont icon-play-video icon-pause-video"></span>
            <!-- 停止 -->
            <span class="iconfont icon-stop-video"></span>
            <!-- 时间戳 -->
            <span class="timeStamp"> 00:00:00 / 00:00:00 </span>
            <!-- 快退 -->
            <span class="iconfont icon-fast-rewind"></span>
            <!-- 慢放 -->
            <span class="iconfont icon-slow-release"></span>
            <!-- 当前控制状态显示 -->
            <span class="controlStatus">播放中</span>
            <!-- 快放 -->
            <span class="iconfont icon-quick-release"></span>
            <!-- 快进 -->
            <span class="iconfont icon-fast-forward"></span>
          </div>
        </div>
        <div class="rightControl">
          <!-- 音量控制 -->
          <div class="volumeControl">
            <span class="iconfont icon-volume"></span>
            <div class="volumeControlProgress hide">
              <span class="volumeValue">100</span>
              <input
                class="volumeRange"
                type="range"
                orient="vertical"
                value="100"
                min="0"
                max="100"
              />
            </div>
          </div>
          <!-- 码流类型——PC -->
          <div class="streamTypeWrap">
            <span class="streamType" value="1">标清</span>
            <div class="typeOptions hide">
              <span class="sd activeResolution" value="1">标清</span>
              <span class="hd none" value="2">高清</span>
            </div>
          </div>
          <!-- 码流类型——手机端 -->
          <div class="streamTypeWrapPhone">
            <span class="streamTypePhone" value="1">标清</span>
          </div>
          <!-- 下载/停止下载 -->
          <!-- <span class="iconfont icon-download"></span> -->
          <!-- 全屏/退出全屏 -->
          <span class="iconfont icon-amplify"></span>
        </div>
      </div>
    </div>
    <!-- 切换辅流 -->
    <div class="switchStreamWrap">
      <span class="iconfont icon-switch-screen"></span>
    </div>
  </body>

  <script src="./jquery-1.11.3.min.js"></script>
  <script src="./opensource/sonic.js"></script>
  <script src="./common.js"></script>
  <script src="./pcm-player.js"></script>
  <script src="./performance.js"></script>
  <script src="./webgl.js"></script>
  <script src="./player.js"></script>
  <script src="./opensource/canvas2image.js"></script>
  <script src="./streamedian.js"></script>
  <script src="./AVStreamPlayer.js"></script>
  <script src="./RecordDownloadModule.js"></script>
  <script src="./libffmpeg.js"></script>
  <script src="./opensource/StreamSaver/ponyfill.min.js"></script>
  <script src="./opensource/StreamSaver/StreamSaver.js"></script>
  <script>
    $(function() {
      updateSessionTime();
      InitVideoPlayer("auxiliaryStream", 0);
      InitVideoPlayer("mainStream", 1);
      SetControlCallback(player);
      clicks();
      window.parent.postMessage("I'm loaded");
      // 测试假数据
      // coreSDKPlay(tracksInfo.rtsp_pull_addr, tracksInfo.tracks, tracksInfo.playType, tracksInfo.begin_time, tracksInfo.end_time);
    });
    // 监听父组件传的信息
    var tracksInfo = "",
      param = ""; //data码流信息,param请求参数
    window.addEventListener("message", function(data) {
      // 获取父组件码流信息
      if (data) {
        if(data.data.data.isUpdateUserSig)
          {
            player.updateUserSig(data.usersig);
            return;
          }
        let receiveInfo = data.data;
        if (typeof receiveInfo == "string") {
          handleScreen(receiveInfo);
        } else if (typeof receiveInfo == "object") {
          // 收到的码流信息
          tracksInfo = receiveInfo.data;
          // 处理信息
          handleTracksInfo(tracksInfo);
            coreSDKPlay(
            tracksInfo.rtsp_pull_addr,
            tracksInfo.tracks,
            tracksInfo.playType,
            tracksInfo.begin_time,
            tracksInfo.end_time,
            tracksInfo.usersig,
            tracksInfo.srtnAddress
          );
        }
      }
    });
    // 处理画面布局
    function handleScreen(receiveInfo) {
      // 更改布局(并列、大小、单个画面)(手机/PC)
      if (
        receiveInfo == "m-side-screen" ||
        receiveInfo == "m-large-small-screen" ||
        receiveInfo == "m-single-screen" ||
        receiveInfo == "side-screen" ||
        receiveInfo == "large-small-screen" ||
        receiveInfo == "single-screen"
      ) {
        $(".canvasWrap")
          .removeClass(
            "side-screen single-screen large-small-screen m-side-screen m-single-screen m-large-small-screen"
          )
          .addClass(receiveInfo);
      } else if (
        receiveInfo == "horizontalScreen" ||
        receiveInfo == "verticalScreen"
      ) {
        // 横竖屏(手机)
        $(".canvasWrap")
          .removeClass("horizontalScreen verticalScreen")
          .addClass(receiveInfo);
        // 隐藏音量控制
        $(".volumeControl").hide();
        // 隐藏PC端高清标清切换
        $(".streamTypeWrap").hide();
        $(".streamTypeWrapPhone").show();
      }
    }
    // 处理父组件传过来的数据
    function handleTracksInfo(tracksInfo) {
      // 获取详情的请求参数
      param = tracksInfo.param;
      // 辅流切换按钮显隐
      if (tracksInfo.auxiliaryFlag) {
        $(".switchStreamWrap").show();
      }
      // 直播隐藏录像控制操作
      if (tracksInfo.playType == 0) {
        $(".controls .liveControl").show();
        $(".controlWrap .videoProgress")
          .hide()
          .next()
          .addClass("liveControl");
        $(".controls .recordControl").hide();
      }
      // 高清标清是否可选择
      let tracks = tracksInfo.tracks;
      let subLen = 0;
      for (let i = 0; i < tracks.length; i++) {
        if (tracks[i].type == "video") {
          if (tracks[i].subtracks.length > 1) {
            subLen += 1;
          }
        }
      }
      if (subLen) {
        $(".streamTypeWrap").addClass("aviable"); //PC端标清高清切换
        $(".streamTypeWrapPhone").addClass("aviable"); //手机端标清高清切换
      } else {
        $(".streamTypeWrap").removeClass("aviable");
        $(".streamTypeWrapPhone").removeClass("aviable");
        let streamTypeSpanPC = $(".streamTypeWrap .streamType");
        let streamTypeSpanPhone = $(".streamTypeWrapPhone .streamTypePhone");
        for (let i = 0; i < tracks.length; i++) {
          if (tracks[i].type == "video") {
            if (tracks[i].subtracks[0].resolution == 1) {
              streamTypeSpanPC.text("标清");
              streamTypeSpanPhone.text("标清");
            } else {
              streamTypeSpanPC.text("高清");
              streamTypeSpanPhone.text("高清");
            }
          }
        }
      }
    }
    // 点击集合
    function clicks() {
      /* 直播 */
      $(".livePlay").click(function() {
        let className = $(this).attr("class");
        if (className.indexOf("icon-pause-video") > -1) {
          $(this).removeClass("icon-pause-video");
          player.stop();
        } else {
          $(this).addClass("icon-pause-video");
          coreSDKPlay(
            tracksInfo.rtsp_pull_addr,
            tracksInfo.tracks,
            tracksInfo.playType,
            tracksInfo.begin_time,
            tracksInfo.end_time
          );
        }
        hideVolumTypeOptions();
      });
      /* 录播 */
      // 暂停/恢复
      $(".recordControl .icon-play-video").click(function() {
        let className = $(this).attr("class");
        if (className.indexOf("icon-pause-video") > -1) {
          $(this).removeClass("icon-pause-video");
          player.pause();
        } else {
          $(this).addClass("icon-pause-video");
          player.resume();
        }
        hideVolumTypeOptions();
      });
      // 停止
      $(".recordControl .icon-stop-video").click(function() {
        for (var index in ControlMap) {
          var statuscom = ControlMap[index].statusTrack;
          statuscom.text("录像播放");
        }
        player.stop();
        hideVolumTypeOptions();
      });
      // 快退
      $(".recordControl .icon-fast-rewind").click(function() {
        let className = $(this).attr("class");
        if (className.indexOf("disable") == -1) {
          player.ScaleDown();
          hideVolumTypeOptions();
        }
      });
      // 慢放
      $(".recordControl .icon-slow-release").click(function() {
        player.SpeedDown();
        hideVolumTypeOptions();
      });
      // 快放
      $(".recordControl .icon-quick-release").click(function() {
        player.SpeedUp();
        hideVolumTypeOptions();
      });
      // 快进
      $(".recordControl .icon-fast-forward").click(function() {
        let className = $(this).attr("class");
        if (className.indexOf("disable") == -1) {
          player.ScaleUp();
          hideVolumTypeOptions();
        }
      });
      /* 音量显隐 */
      $(".volumeControl .icon-volume").click(function() {
        $(".volumeControlProgress").toggleClass("hide");
        $(".typeOptions").addClass("hide");
      });
      /* 高清/标清选择显隐 */
      $(document).on(
        "click",
        ".streamTypeWrap.aviable .streamType",
        function() {
          $(".typeOptions").toggleClass("hide");
          $(".volumeControlProgress").addClass("hide");
        }
      );
      /* 高清/标清选择——PC */
      $(document).on(
        "click",
        ".streamTypeWrap .typeOptions span.none",
        function() {
          let selectedType = $(this).text();
          $(".streamTypeWrap .streamType").text(selectedType);
          $(".typeOptions").addClass("hide");
          $(this)
            .addClass("activeResolution")
            .removeClass("none")
            .siblings()
            .removeClass("activeResolution")
            .addClass("none");
          getLiveUrl($(this).attr("value"));
        }
      );
      /* 高清/标清选择——手机端 */
      $(document).on("click", ".streamTypeWrapPhone.aviable", function() {
        let resolutionSpan = $(this).find("span");
        if (resolutionSpan.attr("value") == 1) {
          resolutionSpan.attr("value", 2);
          // 重新获取url
          getLiveUrl(resolutionSpan.attr("value"));
          resolutionSpan.text("高清");
        } else {
          resolutionSpan.attr("value", 1);
          // 重新获取url
          getLiveUrl(resolutionSpan.attr("value"));
          resolutionSpan.text("标清");
        }
      });
      function startRecordDownload(
        url,
        socketType,
        port,
        downloadTracks,
        playType,
        begintime,
        endtime,
        downloadFileName
      ) {
        var websocketurl =
          socketType +
          "://" +
          url.substring("rtsp://".length, url.indexOf("/", "rtsp://".length)) +
          "/";
        var portIndex = 0;
        if (websocketurl.indexOf("[") > -1 && websocketurl.indexOf("]") > -1) {
          //ipv6
          portIndex = websocketurl.indexOf(":", websocketurl.indexOf("]"));
        } else {
          portIndex = websocketurl.indexOf(
            ":",
            websocketurl.indexOf("://") + 2
          );
        }
        websocketurl =
          websocketurl.substring(0, portIndex) + ":" + port.toString() + "/";

        var recordRange = null;
        if (begintime && endtime) {
          //iPhone中的safari无法解释 YYYY-MM-DD HH:mm:ss 或者YYYY/MM/DD HH:mm:ss这样的时间格式,而谷歌火狐等浏览器对这样的格式做了扩展,
          //iPhone中的safari所支持的格式为 YYYY,MM, DD,HH,mm,ss,这个问题纠结我大半天,真的好想把苹果的程序员拉出去枪毙10分钟,太TM特立独行了。气人
          var begintimeNew = begintime.split(/[- : \/]/);
          var endtimeNew = endtime.split(/[- : \/]/);
          let begin = new Date(
            begintimeNew[0],
            begintimeNew[1] - 1,
            begintimeNew[2],
            begintimeNew[3],
            begintimeNew[4],
            begintimeNew[5]
          );
          let end = new Date(
            endtimeNew[0],
            endtimeNew[1] - 1,
            endtimeNew[2],
            endtimeNew[3],
            endtimeNew[4],
            endtimeNew[5]
          );
          recordRange = `${GetTimeString(begin)}-${GetTimeString(end)}`;
        }

        var playespeed = 4;
        downloader.startRecordDownload(
          url,
          websocketurl,
          downloadTracks,
          playType,
          recordRange,
          playespeed,
          downloadFileName
        );
      }
      /* 下载 */
      $(document).on("click", ".icon-download", function() {
        startRecordDownload(
          tracksInfo.rtsp_pull_addr,
          "wss",
          50001,
          null,
          1,
          tracksInfo.begin_time,
          tracksInfo.end_time,
          tracksInfo.filename
        );
      });

      /* 停止下载 */
      $(document).on("click", ".icon-download-disabled", function() {
        downloader.manuallyStopRecordDownload();
      });

      /* 全屏/退出全屏 */
      $(document).on("click", ".icon-amplify", function() {
        launchFullscreen($(".conferenceLive")[0]);
        // 图标变化
        $(this)
          .addClass("icon-shrink")
          .removeClass("icon-amplify");
        hideVolumTypeOptions();
        $(".canvasWrap").addClass("fullScreen");
      });
      $(document).on("click", ".icon-shrink", function() {
        exitFullscreen();
        $(this)
          .removeClass("icon-shrink")
          .addClass("icon-amplify");
        hideVolumTypeOptions();
        $(".canvasWrap").removeClass("fullScreen");
      });
      /* 切换辅流 */
      $(".icon-switch-screen").click(function() {
        $(".canvasWrap").toggleClass("switchStream");
        hideVolumTypeOptions();
      });
    }
    var player = "",
      downloader = null,
      localcontrolset = "",
      ControlLists = [],
      ControlMap = {},
      currentTime = 0;
    //初始化播放器
    function InitVideoPlayer(canvasid, index) {
      // 实例化播放器
      if (player == "") {
        player = new Player();
        downloader = new Player(1); //1 表示录像下载模块
        downloader.SetPlayerStateCallback((state) => {
          if (state == playerStateLoading || state == playerStateUnloading) {
            //开始下载
            //切换
            console.log("开始下载");
            $(".icon-download")
              .addClass("icon-download-disabled")
              .removeClass("icon-download");
          } else if (state == playerStateIdle) {
            //下载结束
            //切换
            console.log("结束下载");
            $(".icon-download-disabled")
              .addClass("icon-download")
              .removeClass("icon-download-disabled");
          }
        });
      }
      getControlLists(canvasid, index);
      player.setControl(localcontrolset.canvas, index);
    }
    function getControlLists(canvasid, index) {
      //VCR状态回调函数设置
      localcontrolset = {
        canvas: document.getElementById(canvasid),
        loadingDiv: $(".loading"), //确定初始化状态,播放状态回调
        statusTrack: $(".controlStatus"), //VCR状态回调
        timeTrack: $(".videoRange"), //当前播放进度
        timeLabel: $(".timeStamp"), //总时长
        canvasid: index,
      };
      ControlLists.push(localcontrolset);
    }
    function SetControlCallback(player) {
      //VCR状态回调
      player.setVCRStatusCallback((data) => {
        for (var index in ControlMap) {
          var statuscom = ControlMap[index].statusTrack;
          if (statuscom) {
            if (data.pause) {
              statuscom.text("暂停");
            } else if (data.Scale != 1) {
              let scale = data.Scale;
              if (scale > 1) {
                statuscom.text("快进:X" + scale);
              } else {
                statuscom.text("快退:X" + scale);
              }
              // 直播业务中心控制到8倍
              if (scale == 8 || scale == 16) {
                $(".icon-fast-forward").addClass("disable");
              } else if (scale == -8 || scale == -16) {
                $(".icon-fast-rewind").addClass("disable");
              } else {
                $(".icon-fast-forward").removeClass("disable");
                $(".icon-fast-rewind").removeClass("disable");
              }
            } else if (data.Speed != 1) {
              if (data.Speed > 1) {
                statuscom.text("快放:x" + data.Speed.toString());
              } else {
                statuscom.text("慢放:x" + data.Speed.toString());
              }
            } else {
              statuscom.text("录像播放");
            }
          }
        }
        if (data) {
          if (data.pause) {
            $(".icon-play-video").removeClass("icon-pause-video");
          } else {
            $(".icon-play-video").addClass("icon-pause-video");
          }
        }
      });
      //码流诊断、录像播放进度回调
      player.setPlayProgressCallback((info, playType) => {
        if (info) {
          for (var index in ControlMap) {
            var data = null;
            if (!info[index]) {
              continue;
            } else {
              data = info[index];
            }
            var videoInfoCom = ControlMap[index].videoinfocom;
            var timeTrack = ControlMap[index].timeTrack;
            var timeLabel = ControlMap[index].timeLabel;

            if (playType == kRealPlay) {
              return;
            }
            if (timeTrack) {
              currentTime = data.current;
              timeTrack.val(data.current);
              progressBar.css(
                "background",
                "-webkit-linear-gradient(top, #059CFA, #059CFA) 0% 0% / " +
                  (data.current * 100) / data.durnation +
                  "% 100% no-repeat rgba(255, 255, 255, 0.3)"
              );
            }
            if (timeLabel) {
              timeLabel.text(
                formatTime(data.current) + "/" + formatTime(data.durnation)
              );
            }
          }
        }
      });
      //  播放状态回调
      player.SetPlayerStateCallback((state) => {
        if (state == playerStateLoading || state == playerStateUnloading) {
          $(".loading").show();
          $(".controlWrap").hide();
        } else {
          $(".loading").hide();
          $(".controlWrap").show();
        }
      });
      //将canvasID和trackid对应起来
      player.SettrackIDCallback((trackid, canvasid) => {
        for (var index in ControlLists) {
          if (ControlLists[index].canvasid == canvasid) {
            ControlMap[trackid] = ControlLists[index];
            ControlLists.splice(index);
          }
        }
      });
    }
    function format(i, length) {
      let len = i.toString().length;
      let id = "";
      for (let i = 1; i <= length - len; i++) {
        id = 0 + id;
      }
      return id + i.toString();
    }

    function GetTimeString(date) {
      //点直播流媒体不要.000这样的毫秒数  /*.${this.format(this.date.getUTCMilliseconds(), 3)}*/
      return `${date.getFullYear()}${format(date.getMonth() + 1, 2)}${format(
        date.getDate(),
        2
      )}T${format(date.getHours(), 2)}${format(date.getMinutes(), 2)}${format(
        date.getSeconds(),
        2
      )}.${format(date.getMilliseconds(), 3)}Z`;
    }

    function formatTime(s) {
      var h =
        Math.floor(s / 3600) < 10
          ? "0" + Math.floor(s / 3600)
          : Math.floor(s / 3600);
      var m =
        Math.floor((s / 60) % 60) < 10
          ? "0" + Math.floor((s / 60) % 60)
          : Math.floor((s / 60) % 60);
      var s =
        Math.floor(s % 60) < 10 ? "0" + Math.floor(s % 60) : Math.floor(s % 60);
      return (result = h + ":" + m + ":" + s);
    }
    Date.prototype.Format = function(fmt) {
      var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds(), //毫秒
      };
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
      return fmt;
    };

    // 修改wsurl端口
    function changeURLport(websocketurl) {
      var portIndex = 0;
      var port = 50001;
      if (websocketurl.indexOf("[") > -1 && websocketurl.indexOf("]") > -1) {
        //ipv6
        portIndex = websocketurl.indexOf(":", websocketurl.indexOf("]"));
      } else {
        portIndex = websocketurl.indexOf(":", websocketurl.indexOf("://") + 2);
      }
      websocketurl =
        websocketurl.substring(0, portIndex) + ":" + port.toString() + "/";
      return websocketurl;
    }
    //开始播放
    function coreSDKPlay(
      rtspurl,
      tracks,
      playtype = 0,
      begintime = null,
      endtime = null,
      usersig,
      srtnAddress
    ) {
      initProgressBar();
      console.log("coreSDKPlay", rtspurl, tracks, usersig, srtnAddress);
      // 性能上报
      player.setAccessgwIP(srtnAddress);
      player.setUserSig(usersig);
      var websocketurl =
        "wss://" +
        rtspurl.substring(
          "rtsp://".length,
          rtspurl.indexOf("/", "rtsp://".length)
        ) +
        "/";
      var recordRange = null;
      let qosDelayMS = 0;
      if (playtype == 1) {
        if (begintime && endtime) {
          var begintimeNew = begintime.split(/[- : \/]/);
          var endtimeNew = endtime.split(/[- : \/]/);
          let begin = new Date(
            begintimeNew[0],
            begintimeNew[1] - 1,
            begintimeNew[2],
            begintimeNew[3],
            begintimeNew[4],
            begintimeNew[5]
          );
          let end = new Date(
            endtimeNew[0],
            endtimeNew[1] - 1,
            endtimeNew[2],
            endtimeNew[3],
            endtimeNew[4],
            endtimeNew[5]
          );
          recordRange = `${GetTimeString(begin)}-${GetTimeString(end)}`;
        }
      }
      websocketurl = changeURLport(websocketurl);
      // for (var index in ControlMap) {
      //   ControlLists.push(ControlMap[index]);
      // }
      // ControlMap = {};
      // rtspurl ? player.play(rtspurl, websocketurl, playtype = 1, recordRange, tracks, qosDelayMS) : null;
      if (rtspurl) {
        if (
          0 ==
          player.play(
            rtspurl,
            websocketurl,
            playtype,
            recordRange,
            tracks,
            qosDelayMS
          )
        ) {
          for (var index in ControlMap) {
            ControlLists.push(ControlMap[index]);
          }
          ControlMap = {};

          player.SetVolume(100);
        }
      }
      return true;
    }
    var progressBar = $(".videoRange"); //视频进度条
    var volume = $(".volumeRange"); //音量进度条
    var dragFlag = false;
    // 初始化进度条
    function initProgressBar() {
      volume.volumeRangeSlider(100); //初始化音量进度条
      let date =
        (new Date(tracksInfo.end_time) - new Date(tracksInfo.begin_time)) /
        1000;
      if (isNaN(date)) return;
      progressBar.attr("max", date);
      progressBar.videoRangeSlider(date); //初始化视频进度条效果
    }
    //  视频进度条滑动时的样式
    $.fn.videoRangeSlider = function(max) {
      let $input = $(this);
      $input.bind("input", function(e) {
        dragFlag = false;
        player.setDragState(dragFlag);
        // 录像计算总时长,用于拖动进度条展示时长
        let videoTotalDuration = player.getDurationTime();
        $input.attr("value", this.value);
        $input.css(
          "background",
          "-webkit-linear-gradient(top, #059CFA, #059CFA) 0% 0% / " +
            (this.value * 100) / max +
            "% 100% no-repeat rgba(255, 255, 255, 0.3)"
        );
        $(".timeStamp").text(
          formatTime(this.value) + "/" + formatTime(videoTotalDuration)
        );
      });
    };
    //拉动进度条后调用的接口
    progressBar.change(function() {
      dragFlag = true;
      player.setDragState(dragFlag);
      player.Seek(this.value);
    });
    // 音量进度条滑动
    $.fn.volumeRangeSlider = function(max) {
      let $input = $(this);
      $input.bind("input", function(e) {
        $input.attr("value", this.value);
        $(".volumeValue").text(this.value);
        $input.css(
          "background",
          "-webkit-linear-gradient(top, #059CFA, #059CFA) 0% 0% / " +
            (this.value * 100) / max +
            "% 100% no-repeat rgba(255, 255, 255, 0.3)"
        );
      });
    };
    volume.change(function() {
      if (this.value === 0) {
        //0为静音
        player.SetMute(0);
      } else {
        player.SetVolume(this.value); // 滑动设置音量
      }
    });
    // 高清标清切换重新发请求获取详情
    function getLiveUrl(val) {
      // console.log(val, param, tracksInfo)
      let data = JSON.stringify(param);
      // ajaxUrl[0]获取直播详情,ajaxUrl[1]获取录像详情;tracksInfo.playType:0直播,1录像
      let ajaxUrl = [
        "/api/srtn-live-manage/v1/lives/audience/detail",
        "/api/srtn-live-manage/v1/records/playurl",
      ];
      $.ajax({
        url: ajaxUrl[tracksInfo.playType],
        type: "post",
        data: data,
        crossDomain: true,
        dataType: "json",
        beforeSend: function(req) {
          req.setRequestHeader("Content-Type", "application/json"); ///加这一行解决问题
        },
        success: function(res) {
          if (res.code == 0) {
            headleData(res, val);
          }
        },
        error: function(status, error) {
          console.log("status:", status);
          console.log("error:", error);
        },
      });
    }
    // 滤掉高清或标清码流
    function headleData(res, val) {
      let pull_addr = "";
      // 直播重新获取的url
      if (res.row) {
        if (res.row.rtsp_pull_addr != null) {
          pull_addr = res.row.rtsp_pull_addr;
        } else {
          pull_addr = res.row.rtsp_pull_addr_ipv6;
        }
      } else {
        pull_addr = res.url;
      }
      // 根据选择的高清标清筛选出对应tracks
      let tracks = JSON.parse(JSON.stringify(tracksInfo.tracks));
      for (let i = 0; i < tracks.length; i++) {
        if (tracks[i].type == "video") {
          // 当有两路流时才筛选出高清或标清码流,否则切换也只播那一路流
          if (tracks[i].subtracks.length > 1) {
            for (let j = 0; j < tracks[i].subtracks.length; j++) {
              if (tracks[i].subtracks[j].resolution == val) {
                tracks[i].subtracks = [tracks[i].subtracks[j]];
              }
            }
          }
        }
      }
      coreSDKPlay(
        pull_addr,
        tracks,
        tracksInfo.playType,
        tracksInfo.begin_time,
        tracksInfo.end_time
      );
    }
    //進入全屏
    function launchFullscreen(element) {
      //此方法不可以在異步任務中執行,否則火狐無法全屏
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) {
        element.mozRequestFullScreen();
      } else if (element.msRequestFullscreen) {
        element.msRequestFullscreen();
      } else if (element.oRequestFullscreen) {
        element.oRequestFullscreen();
      } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen();
      }
    }
    //退出全屏
    function exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.oRequestFullscreen) {
        document.oCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    }
    // 监听鼠标点击事件,更新会话操作纪录时间
    function updateSessionTime() {
      $(document).mousedown(function() {
        localStorage.setItem("lastTime", new Date().getTime());
      });
    }
    // 隐藏音量进度条和高清标清选择框
    function hideVolumTypeOptions() {
      $(".typeOptions").addClass("hide");
      $(".volumeControlProgress").addClass("hide");
    }

    // 测试数据
    // tracksInfo = {
    //   begin_time: "2021-03-11 06:51:38",
    //   end_time: "2021-03-11 06:57:45",
    //   playType: 1,
    //   rtsp_pull_addr: "rtsp://10.229.10.169:8000/home/zxsrtn/record/record3/2H264_1PCMA/20210311T145500Z00000.mpg?trackid=1,2,5&operation=play&urltype=0&begintime=20210311065138&endtime=20210311065745&time=20210325001607+00&life=36000&cryptmode=0304&crypt=F7557956AAC984BE74214678DE3C092A688BEEB51E79ABF456FA37FDD9727919",
    //   tracks: []
    // }
    // tracksInfo.tracks.push({
    //   type: "video",
    //   subtracks: [{
    //     code_format: "H264",
    //     pull_addr: "aaa",
    //     push_addr: "bbb",
    //     resolution: 1,
    //     status: 0,
    //     trackid: 1
    //   }, {
    //     code_format: "H264",
    //     pull_addr: "aaa",
    //     push_addr: "bbb",
    //     resolution: 1,
    //     status: 0,
    //     trackid: 2
    //   }, {
    //     code_format: "H264",
    //     pull_addr: "aaa",
    //     push_addr: "bbb",
    //     resolution: 1,
    //     status: 0,
    //     trackid: 3
    //   }, {
    //     code_format: "H264",
    //     pull_addr: "aaa",
    //     push_addr: "bbb",
    //     resolution: 1,
    //     status: 0,
    //     trackid: 4
    //   }]
    // });
    // tracksInfo.tracks.push({
    //   type: "audio",
    //   subtracks: [{
    //     code_format: "G711",
    //     pull_addr: "aaa",
    //     push_addr: "bbb",
    //     resolution: 2,
    //     status: 0,
    //     trackid: 5
    //   }]
    // });
  </script>
</html>

上一篇:vue-router多个组件模板放入同一个页面中


下一篇:微信小程序:WeUI组件库的使用