<template>
  <div class="voiceAppMainViews" v-if="showDecide">
    <div class="voiceAppSmallTitle">语音申请</div>
    <img
      src="../../../../assets/images/truckTuPian/close.png"
      class="voiceAppClose"
      @click="voiceAppCloseFn()"
    />
    <div class="voiceAppContent">
      <div class="voiceAppContent_1">
        <div class="voiceAppContent_1_1">选择车队：</div>
        <el-select
          v-model="selectCarFleet"
          placeholder="请选择车队"
          style="width: 20vw"
          @change="toSearch()"
        >
          <el-option
            v-for="(item, index) in carFleetData"
            :key="index"
            :label="item.name"
            :value="item.name"
            style="font-size: 18px"
          ></el-option>
        </el-select>
        <!-- <el-input v-model="searchText" placeholder="请输入车牌号" style="width:19vw;"></el-input>
				<el-button type="primary" round class="voiceAppContent_1_btn1" @click="toSearch()">查询</el-button> -->
      </div>
      <div class="voiceAppContent_2">
        <div>
          <div class="voiceAppContent_2_title">
            <div>车牌号</div>
          </div>
          <div class="voiceAppContent_2_content">
            <el-checkbox-group v-model="selectCarRadioArray">
              <el-checkbox
                v-for="(item, index) in carsInforData"
                :label="item"
                :key="index"
                class="voiceAppContent_2_content_checkboxs"
              >
                <div style="width: 20vw; text-align: center">
                  {{ item.number == "pcBigScreen" ? "调度中心" : item.number }}
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
        <div style="position: relative">
          <div class="voiceAppContent_2_title">
            <div>已选中车辆</div>
          </div>
          <div class="voiceAppContent_2_3_content">
            <div
              v-for="(item, index) in selectCarRadioArray"
              :key="index"
              class="voiceAppContent_2_content_selectCar"
            >
              <div>
                车牌号：{{
                  item.number == "pcBigScreen" ? "调度中心" : item.number
                }}
              </div>
              <div
                class="voiceAppContent_2_content_selectCar_2"
                @click="cancelSelect(index)"
              >
                <span>×</span>
              </div>
            </div>
          </div>
          <div style="display: flex; justify-content: space-around">
            <!-- <el-button type="primary" round class="toCallStyle tonghuaBtnShow" @click="recStart()" :disabled='tonghuadisabled'>{{tonghua1}}</el-button>
						<el-button type="primary" round class="toCallStyle tonghuaBtnShow" @click="recStop()">结束通话</el-button>
						<el-button type="primary" round class="toCallStyle" @click="recUploadLast()" :disabled='tonghuadisabled'>上传通话</el-button> -->
            <el-button
              type="primary"
              round
              class="toCallStyle"
              @touchstart.native="recStart()"
              @touchend.native="recStop()"
              >发起通话</el-button
            >
          </div>
        </div>
      </div>
      <div style="margin-top: 1vh">
        <img
          style="width: 2.7vw"
          src="../../../../assets/images/truckTuPian/fuxiaobiaotititle.png"
        />
        <span class="voiceAppContent_left_title">当前语音通话情况：</span>
      </div>

      <audio id="audioTemp" controls currentTime autoplay :src="srcUrl" style="display: none"></audio>

      <div class="situationStyle">
        <div
          v-for="(item, index) in videoContentAllArray"
          :key="index"
          class="situation_fa1"
        >
          <img :src="situationPic1" @click="selectSituation(item)" />
          <div @click="selectSituation(item)">来自{{ item.fromUserId }}</div>
          <!-- <span class="el-icon-microphone" @click="selectSituation(item)"></span> -->
          <span
            class="el-icon-delete"
            @click="selectDeleteSituation(index)"
          ></span>
          <!-- <div class="situationNumber" v-if="item.number != 0">{{item.number}}</div> -->
        </div>
      </div>

      <!-- 语音所需内容，隐藏无需展示 -->
      <div class="main" style="display: none">
        <slot name="top"></slot>

        <div class="mainBox">
          <div class="btns">
            <div>
              <button @click="recOpen">打开录音,请求权限</button>
              <button @click="recClose">关闭录音,释放资源</button>
            </div>

            <button @click="recStart">录制</button>
            <button @click="recStop" style="margin-right: 80px">停止</button>

            <span style="display: inline-block">
              <button @click="recPause">暂停</button>
              <button @click="recResume">继续</button>
            </span>
            <span style="display: inline-block">
              <button @click="recPlayLast">播放</button>
              <button @click="recUploadLast">上传</button>
            </span>
          </div>
        </div>

        <div class="mainBox">
          <div
            style="
              height: 100px;
              width: 300px;
              border: 1px solid #ccc;
              box-sizing: border-box;
              display: inline-block;
              vertical-align: bottom;
            "
            class="ctrlProcessWave"
          ></div>
          <div
            style="
              height: 40px;
              width: 300px;
              display: inline-block;
              background: #999;
              position: relative;
              vertical-align: bottom;
            "
          >
            <div
              class="ctrlProcessX"
              style="height: 40px; background: #0b1; position: absolute"
              :style="{ width: powerLevel + '%' }"
            ></div>
            <div
              class="ctrlProcessT"
              style="padding-left: 50px; line-height: 40px; position: relative"
            >
              {{ duration + "/" + powerLevel }}
            </div>
          </div>
        </div>

        <div class="mainBox">
          <audio ref="LogAudioPlayer" style="width: 100%"></audio>

          <div class="mainLog"></div>
        </div>

        <div
          v-if="recOpenDialogShow"
          style="
            z-index: 99999;
            width: 100%;
            height: 100%;
            top: 0;
            left: 0;
            position: fixed;
            background: rgba(0, 0, 0, 0.3);
          "
        ></div>

        <slot name="bottom"></slot>
      </div>
    </div>
  </div>
</template>

<script>
import {
  httpGet,
  httpPostForJson,
  putForJson,
  httpDelForJson,
} from "@/common/httpBean.js";
import { carFleetQuery, vehicleInformationQuery } from "@/axios/api.js";
import situationPic1 from "../../../../assets/images/truckTuPian/tonghuazhong1.png";
import situationPic2 from "../../../../assets/images/truckTuPian/tonghuazhong2.png";
//加载必须要的core，demo简化起见采用的直接加载类库，实际使用时应当采用异步按需加载
import Recorder from "recorder-core";
// //需要使用到的音频格式编码引擎的js文件统统加载进来，这些引擎文件会比较大
import "recorder-core/src/engine/mp3";
import "recorder-core/src/engine/mp3-engine";
// //可选的扩展
import "recorder-core/src/extensions/waveview";
import { config as appConfig } from '@/config.js';

export default {
  data() {
    return {
      srcUrl: null,
      websocket: null,
      heartbeatTimer: null,
      userName1: "",
      videoContent: null,
      videoContentUserName: null,
      //Rec:Recorder,

      type: "mp3",
      bitRate: 16,
      sampleRate: 16000,

      rec: 0,
      duration: 0,
      powerLevel: 0,

      recOpenDialogShow: 0,
      logs: [],
      showDecide: false,
      selectCarFleet: "",
      searchText: "",
      carFleetData: [],
      carsInforData: [],
      selectCarRadioArray: [],
      situationPic1: situationPic1,
      situationPic2: situationPic2,
      tonghuadisabled: false,
      tonghua1: "开始通话",
      carAllNumberString: "",
      videoContentAllArray: [],
      resultBlob: null,
    };
  },
  mounted() {
    let that = this;
    document.onkeydown = function (e) {
      if (e.keyCode == 178) {
        that.recStart();
      }
      if (e.keyCode == 179) {
        that.recStop();
      }
    };
  },
  methods: {
    loadData(value, tishi) {
      this.showDecide = true;
      this.selectCarFleet = "";
      this.searchText = "";
      this.selectCarRadioArray = [];
      this.userName1 = value; //车牌号
      this.srcUrl = null;
      this.recOpen();
      //车队
      httpGet(carFleetQuery, { size: 9999, page: 0 }).then((res) => {
        if (res.code == 200) {
          this.carFleetData = res.data.content;
        }
      });
      if (tishi) {
        this.carsInforData = [{ number: "pcBigScreen" }];
        this.selectCarRadioArray = [{ number: "pcBigScreen" }];
      } else {
        this.loadData2();
      }
    },
    //获取车辆数据
    loadData2() {
      let query = {};
      query.size = 9999;
      query.page = 0;
      query.number = this.searchText;
      query.road = this.selectCarFleet;
      //获取车辆信息并添加调度大屏的语音id
      httpGet(vehicleInformationQuery, query).then((res) => {
        if (res.code == 200) {
          let obj1 = [];
          res.data.content.forEach((item, index) => {
            if (item.odo != 0) {
              obj1.push(item);
            }
          });
          obj1.unshift({ number: "pcBigScreen" });
          this.carsInforData = obj1;
        }
      });
    },
    //页面刚进入时开启长连接
    loadData3(value) {
      this.userName1 = value; //车牌号
      this.initWebSocket();
      this.heartbeatTimer = setInterval(() => {
        this.reconnect();
      }, 6000);
      let str1 = localStorage.getItem(this.userName1 + "voiceData");
      if (!str1) {
        return;
      } else {
        let arr2 = JSON.parse(str1);
        this.videoContentAllArray = arr2;
        this.$parent.audioDataFn(arr2);
      }
    },
    //关闭语音申请组件
    voiceAppCloseFn() {
      this.showDecide = false;
      this.selectCarFleet = "";
      this.searchText = "";
      this.selectCarRadioArray = [];
      this.recClose();
      this.$parent.selectFunction = 0;
    },
    //关闭心跳以及关闭长连接
    xintiaoCloseFn() {
      //页面销毁时关闭长连接
      this.websocketclose();
      //关闭心跳
      if (this.heartbeatTimer) {
        clearInterval(this.heartbeatTimer);
      }
    },
    toSearch() {
      this.loadData2();
    },
    cancelSelect(index) {
      let handleArray = [...this.selectCarRadioArray];
      handleArray.splice(index, 1);
      this.selectCarRadioArray = handleArray;
    },

    //初始化weosocket
    initWebSocket() {
      const wsuri = "ws://"+appConfig.ws+"/webSocket" + "/" + this.userName1;
      this.websocket = new WebSocket(wsuri);
      this.websocket.onopen = this.websocketonopen;
      this.websocket.onerror = this.websocketonerror;
      this.websocket.onmessage = this.websocketonmessage;
      this.websocket.onclose = this.websocketclose;
      this.websocketonmessage();
    },
    //WebSocket连接成功
    websocketonopen() {
      console.log("WebSocket连接成功");
    },
    //WebSocket连接错误
    websocketonerror(e) {
      console.log("WebSocket连接发生错误");
    },
    //WebSocket数据接收
    websocketonmessage(e) {
      //console.log('websocketonmessage',e);
      let that = this;
      if (e == undefined) {
        // let str1 = localStorage.getItem(this.userName1 + 'voiceData');
        // if(!str1){
        // 	return
        // }else{
        // 	let arr2 = JSON.parse(str1);
        // 	that.videoContentAllArray = arr2;
        // 	that.$parent.audioDataFn(arr2);
        // }
      } else {
        let str1 = localStorage.getItem(this.userName1 + "voiceData");
        let str2 = JSON.parse(e.data);
        if (str2.fromUserId != this.userName1) {
          that.$parent.tishishoudaoyuyinFn();
          //5秒后自动播放
          setTimeout(function () {
            that.selectSituationIndex(str2, true);
          }, 5000);
        }
        if (!str1) {
          let arr1 = [];
          arr1.unshift(str2);
          that.videoContentAllArray = arr1;
          that.$parent.audioDataFn(arr1);
          localStorage.setItem(
            this.userName1 + "voiceData",
            JSON.stringify(arr1)
          );
        } else {
          let arr2 = JSON.parse(str1);
          arr2.unshift(str2);
          let jinjitongzhi = [];
          let guangbo = [];
          let tonghua = [];
          let qitache = [];
          arr2.forEach((item2, indedx2) => {
            if (item2.fromUserId == "紧急通知") {
              jinjitongzhi.push(item2);
            } else if (item2.fromUserId == "广播") {
              guangbo.push(item2);
            } else if (item2.fromUserId == "通话") {
              tonghua.push(item2);
            } else {
              qitache.push(item2);
            }
          });
          let lastAudioData = [
            ...jinjitongzhi,
            ...guangbo,
            ...tonghua,
            ...qitache,
          ];
          that.videoContentAllArray = lastAudioData;
          that.$parent.audioDataFn(lastAudioData);
          localStorage.setItem(
            this.userName1 + "voiceData",
            JSON.stringify(lastAudioData)
          );
        }
      }
    },
    //WebSocket数据发送
    websocketsend(agentData) {
      this.websocket.send(agentData);
    },
    //WebSocket关闭
    websocketclose(e) {
      console.log("connection closed (" + e + ")");
    },
    //WebSocket重连
    reconnect() {
      var This = this;
      if (this.websocket.readyState === 1) {
        // that.websock.readyState = 1 表示连接成功，可以立即发送信息
        This.websocketonmessage();
      } else if (this.websocket.readyState === 0) {
        // 表示正在连接，设置300ms后发送信息
        setTimeout(function () {
          This.websocketonmessage();
        }, 300);
      } else {
        // 连接未创建或者创建失败，则重新创建连接，并设置500ms后发送信息
        This.initWebSocket();
        setTimeout(function () {
          This.websocketonmessage();
        }, 500);
      }
    },

    recOpen: function () {
      var This = this;
      var rec = (this.rec = Recorder({
        type: This.type,
        bitRate: This.bitRate,
        sampleRate: This.sampleRate,
        onProcess: function (buffers, powerLevel, duration, sampleRate) {
          This.duration = duration;
          This.powerLevel = powerLevel;

          This.wave.input(buffers[buffers.length - 1], powerLevel, sampleRate);
        },
      }));

      This.dialogInt = setTimeout(function () {
        //定时8秒后打开弹窗，用于监测浏览器没有发起权限请求的情况
        This.showDialog();
      }, 8000);

      rec.open(
        function () {
          This.dialogCancel();
          //console.log('录音权限已打开');
          This.reclog(
            "已打开:" +
              This.type +
              " " +
              This.sampleRate +
              "hz " +
              This.bitRate +
              "kbps",
            2
          );

          This.wave = Recorder.WaveView({ elem: ".ctrlProcessWave" });
        },
        function (msg, isUserNotAllow) {
          This.dialogCancel();
          This.reclog(
            (isUserNotAllow ? "UserNotAllow，" : "") + "打开失败：" + msg,
            1
          );
          This.$notify({
            title: "录音权限未打开,请手动开启！"+msg,
            type: "warning",
            duration: 5000,
          });
        }
      );

      This.waitDialogClickFn = function () {
        This.dialogCancel();
        This.reclog("打开失败：权限请求被忽略，用户主动点击的弹窗", 1);
        This.$notify({
          title: "录音权限未打开,请手动开启！",
          type: "warning",
          duration: 5000,
        });
      };
    },
    recClose: function () {
      var rec = this.rec;
      this.rec = null;
      if (rec) {
        rec.close();
        this.reclog("已关闭");
      } else {
        this.reclog("未打开录音", 1);
      }
    },
    recStart: function () {
      if (!this.rec || !Recorder.IsOpen()) {
        //this.reclog("未打开录音",1);
        this.recOpen();
        //return;
      }
      this.rec.start();

      var set = this.rec.set;
      this.reclog(
        "录制中：" +
          set.type +
          " " +
          set.sampleRate +
          "hz " +
          set.bitRate +
          "kbps"
      );
      this.$notify({
        title: "录制中！",
        type: "success",
        duration: 5000,
      });
      this.tonghua1 = "录制中";
      this.tonghuadisabled = true;
    },
    recPause: function () {
      if (this.rec && Recorder.IsOpen()) {
        this.rec.pause();
      } else {
        this.reclog("未打开录音", 1);
      }
    },
    recResume: function () {
      if (this.rec && Recorder.IsOpen()) {
        this.rec.resume();
      } else {
        this.reclog("未打开录音", 1);
      }
    },
    recStop: function () {
      if (!(this.rec && Recorder.IsOpen())) {
        This.reclog("未打开录音", 1);
        This.$notify({
          title: "未打开录音！",
          type: "warning",
          duration: 2500,
        });
        return;
      }
      var This = this;
      var rec = This.rec;
      rec.stop(
        function (blob, duration) {
          if (duration <= 1000) {
            This.$notify({
              title: "按键时间太短",
              type: "warning",
              duration: 2500,
            });
          } else {
            This.reclog("已录制:", "", {
              blob: blob,
              duration: duration,
              rec: rec,
            });
            This.recUploadLast();
          }
        },
        function (s) {
          This.$notify({
            title: "录音失败," + s,
            type: "warning",
            duration: 2500,
          });
          This.reclog("录音失败：" + s, 1);
        }
      );
      this.tonghua1 = "开始通话";
      this.tonghuadisabled = false;
      this.recOpen();
    },

    recPlayLast: function () {
      if (!this.recLogLast) {
        this.reclog("请先录音，然后停止后再播放", 1);
        return;
      }

      this.recplay(this.recLogLast.idx);
    },
    recUploadLast: function () {
      let carNumberString = "";
      this.selectCarRadioArray.forEach((item, index) => {
        carNumberString = carNumberString + item.number + ";";
      });
      carNumberString = carNumberString + this.userName1;
      this.carAllNumberString = carNumberString;

      var This = this;
      if (!this.recLogLast) {
        this.reclog("请先录音，然后停止后再上传", 1);
        This.$notify({
          title: "请先录音，然后停止后再上传！",
          type: "warning",
          duration: 2500,
        });
        return;
      }

      var blob = this.recLogLast.res.blob;
      this.blobToDataURI(blob);

      /***方式一：将blob文件转成base64纯文本编码 ***/
      var reader = new FileReader();
      reader.onloadend = function () {
        var postData = "";
        // postData+="mime="+encodeURIComponent(blob.type);//告诉后端，这个录音是什么格式的，可能前后端都固定的mp3可以不用写
        // postData+="&upfile_b64="+encodeURIComponent((/.+;\s*base64\s*,\s*(.+)$/i.exec(reader.result)||[])[1]) //录音文件内容，后端进行base64解码成二进制
        //postData = btoa(reader.result); //录音文件内容
        postData = This.resultBlob; //录音文件内容

        //发送语音数据
        if (This.websocket.readyState == 1) {
          // that.websock.readyState = 1 表示连接成功，可以立即发送信息
          This.websocketsend(
            `{"toUserId":"${This.carAllNumberString}","contentText":"${postData}","fromUserId":"${This.userName1}"}`
          );
          This.$notify({
            title: "上传成功！",
            type: "success",
            duration: 2500,
          });
        } else if (This.websocket.readyState == 0) {
          // 表示正在连接，设置300ms后发送信息
          setTimeout(function () {
            This.websocketsend(
              `{"toUserId":"${This.carAllNumberString}","contentText":"${postData}","fromUserId":"${This.userName1}"}`
            );
            This.$notify({
              title: "上传成功！",
              type: "success",
              duration: 2500,
            });
          }, 300);
        } else {
          // 连接未创建或者创建失败，则重新创建连接，并设置500ms后发送信息
          This.initWebSocket();
          setTimeout(function () {
            This.websocketsend(
              `{"toUserId":"${This.carAllNumberString}","contentText":"${postData}","fromUserId":"${This.userName1}"}`
            );
            This.$notify({
              title: "上传成功！",
              type: "success",
              duration: 2500,
            });
          }, 500);
        }
      };
      reader.readAsDataURL(blob);

      /***方式二：使用FormData用multipart/form-data表单上传文件***/
      // let form = new FormData();
      // form.append("upfile",blob,"recorder.mp3"); //和普通form表单并无二致，后端接收到upfile参数的文件，文件名为recorder.mp3
      // console.log('form',form);
    },

    reclog: function (msg, color, res) {
      var obj = {
        idx: this.logs.length,
        msg: msg,
        color: color,
        res: res,

        playMsg: "",
        down: 0,
        down64Val: "",
      };
      if (res && res.blob) {
        this.recLogLast = obj;
      }
      this.logs.splice(0, 0, obj);
    },
    recplay: function (idx) {
      var This = this;
      var o = this.logs[this.logs.length - idx - 1];
      o.play = (o.play || 0) + 1;
      var logmsg = function (msg) {
        o.playMsg =
          '<span style="color:green">' +
          o.play +
          "</span> " +
          This.getTime() +
          " " +
          msg;
      };
      logmsg("");

      var audio = this.$refs.LogAudioPlayer;
      audio.controls = true;
      if (!(audio.ended || audio.paused)) {
        audio.pause();
      }
      audio.onerror = function (e) {
        logmsg(
          '<span style="color:red">播放失败[' +
            audio.error.code +
            "]" +
            audio.error.message +
            "</span>"
        );
      };
      audio.src = (window.URL || webkitURL).createObjectURL(o.res.blob);
      audio.play();
    },
    recdown: function (idx) {
      var This = this;
      var o = this.logs[this.logs.length - idx - 1];
      o.down = (o.down || 0) + 1;

      o = o.res;
      var name =
        "rec-" +
        o.duration +
        "ms-" +
        (o.rec.set.bitRate || "-") +
        "kbps-" +
        (o.rec.set.sampleRate || "-") +
        "hz." +
        (o.rec.set.type || (/\w+$/.exec(o.blob.type) || [])[0] || "unknown");
      var downA = document.createElement("A");
      downA.href = (window.URL || webkitURL).createObjectURL(o.blob);
      downA.download = name;
      downA.click();
    },
    recdown64: function (idx) {
      var This = this;
      var o = this.logs[this.logs.length - idx - 1];
      var reader = new FileReader();
      reader.onloadend = function () {
        o.down64Val = reader.result;
      };
      reader.readAsDataURL(o.res.blob);
    },
    getTime: function () {
      var now = new Date();
      var t =
        ("0" + now.getHours()).substr(-2) +
        ":" +
        ("0" + now.getMinutes()).substr(-2) +
        ":" +
        ("0" + now.getSeconds()).substr(-2);
      return t;
    },
    intp: function (s, len) {
      s = s == null ? "-" : s + "";
      if (s.length >= len) return s;
      return ("_______" + s).substr(-len);
    },

    showDialog: function () {
      //我们可以选择性的弹一个对话框：为了防止移动端浏览器存在第三种情况：用户忽略，并且（或者国产系统UC系）浏览器没有任何回调
      if (!/mobile/i.test(navigator.userAgent)) {
        return; //只在移动端开启没有权限请求的检测
      }
      this.recOpenDialogShow = 1;
    },
    dialogCancel: function () {
      clearTimeout(this.dialogInt);
      this.recOpenDialogShow = 0;
    },
    waitDialogClick: function () {
      this.dialogCancel();
      this.waitDialogClickFn();
    },

    //解析base64编码到blob流
    dataURItoBlob(base64Data) {
      //console.log(base64Data);//data:image/png;base64,
      var byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0)
        byteString = atob(base64Data.split(",")[1]);
      //base64 解码
      else {
        byteString = unescape(base64Data.split(",")[1]);
      }
      var mimeString = base64Data.split(",")[0].split(":")[1].split(";")[0]; //mime类型 -- image/png

      // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
      // var ia = new Uint8Array(arrayBuffer);//创建视图
      var ia = new Uint8Array(byteString.length); //创建视图
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      var blob = new Blob([ia], {
        type: mimeString,
      });
      return blob;
    },
    //blob流转base64编码
    blobToDataURI(blob) {
      let that = this;
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function () {
        that.resultBlob = reader.result;
      };
    },
    //播放语音
    selectSituation(item) {
      //注意base64的最后面中括号和引号是不转译的
      let bstr = this.dataURItoBlob(item.contentText);
      const reader1 = new FileReader();
      reader1.readAsArrayBuffer(bstr);
      reader1.onload = (e) => {
        const bufer = e.srcElement.result;
        const blob = this.addWavHeader(bufer, 16000, 16, 1);
        this.srcUrl = (window.URL || webkitURL).createObjectURL(blob);
        setTimeout(function() {
          let au = document.getElementById("audioTemp");
          au.currentTime = 0;
          au.play();
        }, 200);
      };
    },
    //播放语音主页
    selectSituationIndex(item, isNotice) {
      let that = this;
      //注意base64的最后面中括号和引号是不转译的
      let bstr = this.dataURItoBlob(item.contentText);
      const reader1 = new FileReader();
      reader1.readAsArrayBuffer(bstr);
      reader1.onload = (e) => {
        const bufer = e.srcElement.result;
        const blob = this.addWavHeader(bufer, 16000, 16, 1);
        let srcUrlIndex = (window.URL || webkitURL).createObjectURL(blob);
        if (isNotice && item.fromUserId === '紧急通知') {
          that.$parent.audioNoticePlay(srcUrlIndex);
        } else if (isNotice && item.fromUserId === '广播') {
          that.$parent.fanhuiAudioUrl(srcUrlIndex, 2);
        } else {
          that.$parent.fanhuiAudioUrl(srcUrlIndex);
        }
      };
    },
    //删除某个语音
    selectDeleteSituation(index) {
      let str1 = localStorage.getItem(this.userName1 + "voiceData");
      let arr3 = JSON.parse(str1);
      arr3.splice(index, 1);
      this.videoContentAllArray = arr3;
      this.$parent.audioDataFn(arr3);
      localStorage.setItem(this.userName1 + "voiceData", JSON.stringify(arr3));
    },
    addWavHeader(samples, sampleRateTmp, sampleBits, channelCount) {
      const dataLength = samples.byteLength;
      /* 新的buffer类，预留44bytes的heaer空间 */
      const buffer = new ArrayBuffer(44 + dataLength);
      /* 转为 Dataview, 利用API来填充字节 */
      const view = new DataView(buffer);
      let offset = 0;
      /* ChunkID, 4 bytes,  资源交换文件标识符 */
      this.writeString(view, offset, "RIFF");
      offset += 4;
      /* ChunkSize, 4 bytes, 下个地址开始到文件尾总字节数,即文件大小-8 */
      view.setUint32(offset, /* 32 */ 36 + dataLength, true);
      offset += 4;
      /* Format, 4 bytes, WAV文件标志 */
      this.writeString(view, offset, "WAVE");
      offset += 4;
      /* Subchunk1 ID, 4 bytes, 波形格式标志 */
      this.writeString(view, offset, "fmt ");
      offset += 4;
      /* Subchunk1 Size, 4 bytes, 过滤字节,一般为 0x10 = 16 */
      view.setUint32(offset, 16, true);
      offset += 4;
      /* Audio Format, 2 bytes, 格式类别 (PCM形式采样数据) */
      view.setUint16(offset, 1, true);
      offset += 2;
      /* Num Channels, 2 bytes,  通道数 */
      view.setUint16(offset, channelCount, true);
      offset += 2;
      /* SampleRate, 4 bytes, 采样率,每秒样本数,表示每个通道的播放速度 */
      view.setUint32(offset, sampleRateTmp, true);
      offset += 4;
      /* ByteRate, 4 bytes, 波形数据传输率 (每秒平均字节数) 通道数×每秒数据位数×每样本数据位/8 */
      view.setUint32(
        offset,
        sampleRateTmp * channelCount * (sampleBits / 8),
        true
      );
      offset += 4;
      /* BlockAlign, 2 bytes, 快数据调整数 采样一次占用字节数 通道数×每样本的数据位数/8 */
      view.setUint16(offset, channelCount * (sampleBits / 8), true);
      offset += 2;
      /* BitsPerSample, 2 bytes, 每样本数据位数 */
      view.setUint16(offset, sampleBits, true);
      offset += 2;
      /* Subchunk2 ID, 4 bytes, 数据标识符 */
      this.writeString(view, offset, "data");
      offset += 4;
      /* Subchunk2 Size, 4 bytes, 采样数据总数,即数据总大小-44 */
      view.setUint32(offset, dataLength, true);
      offset += 4;
      if (sampleBits === 16) {
        this.floatTo16BitPCM(view, samples);
      } else if (sampleBits === 8) {
        this.floatTo8BitPCM(view, samples);
      } else {
        this.floatTo32BitPCM(view, samples);
      }
      return new Blob([view], { type: "audio/mp3" });
    },
    writeString(view, offset, string) {
      for (let i = 0; i < string.length; i += 1) {
        view.setUint8(offset + i, string.charCodeAt(i));
      }
    },
    floatTo32BitPCM(output, input) {
      const oinput = new Int32Array(input);
      let newoffset = 44;
      for (let i = 0; i < oinput.length; i += 1, newoffset += 4) {
        output.setInt32(newoffset, oinput[i], true);
      }
    },
    floatTo16BitPCM(output, input) {
      const oinput = new Int16Array(input);
      let newoffset = 44;
      for (let i = 0; i < oinput.length; i += 1, newoffset += 2) {
        output.setInt16(newoffset, oinput[i], true);
      }
    },
    floatTo8BitPCM(output, input) {
      const oinput = new Int8Array(input);
      let newoffset = 44;
      for (let i = 0; i < oinput.length; i += 1, newoffset += 1) {
        output.setInt8(newoffset, oinput[i], true);
      }
    },
  },
  beforeDestroy() {
    //页面销毁时关闭长连接
    // this.websocketclose();
    //关闭心跳
    // if(this.heartbeatTimer) {
    // 	clearInterval(this.heartbeatTimer);
    // }
  },
};
</script>

<style scope>
@media screen and (max-width: 901px) {
  .situationStyle img {
    height: 3.5vh;
  }
  .voiceAppContent_2_content_selectCar_2 {
    width: 6vh;
    height: 6vh;
    background-color: rgb(4, 112, 171);
    text-align: center;
    font-size: 30px;
  }
  .voiceAppContent_2_content_checkboxs {
    margin-top: 0.5vh;
  }
  .voiceAppContent_1_btn1 {
    width: 6.5vw;
    font-size: 12px;
    height: 6.5vh;
  }
  .voiceAppContent_1 button {
    padding: 0 !important;
  }
  .voiceAppContent_2 button {
    padding: 0 !important;
    height: 6.5vh;
  }
  .voiceAppContent_1_1 {
    font-size: 12px;
  }
  #audioView {
    position: absolute;
    top: 200px;
    left: 200px;
    z-index: 5;
    background-color: red;
    width: 200px;
    height: 50px;
  }
  .el-input__inner {
    font-size: 18px;
  }
  .voiceAppMainViews {
    position: absolute;
    z-index: 2;
    top: 52%;
    left: 50%;
    height: 90vh;
    width: 60vw;
    background: no-repeat center center
      url("~@/assets/images/truckTuPian/yuyinshenqing1.png");
    background-size: 100% 100%;
    transform: translate(-50%, -50%);
    padding: 12px 30px 0px;
    box-sizing: border-box;
  }
  .voiceAppSmallTitle {
    color: white;
    font-size: 12px;
    text-align: center;
    line-height: 6vh;
    width: 11vw;
    height: 6vh;
    background: no-repeat center center
      url("~@/assets/images/truckTuPian/xiaobiaotikuang.png");
    background-size: 100% 100%;
  }
  .voiceAppClose {
    position: absolute;
    top: 4vh;
    right: 1vw;
    cursor: pointer;
  }
  .voiceAppContent {
    width: 100%;
  }
  .voiceAppContent > div {
    margin-top: 1vh;
  }
  .voiceAppContent_left_title {
    font-size: 13px;
    color: rgb(24, 228, 240);
  }
  .voiceAppContent_1 {
    display: flex;
    justify-content: center;
  }
  .voiceAppContent_1 > div {
    height: 6.5vh;
    line-height: 6.5vh;
    color: rgb(24, 228, 240);
    font-size: 13px;
  }
  .voiceAppContent_1 .el-input--suffix .el-input__inner {
    height: 6.5vh;
    font-size: 12px;
  }
  .voiceAppContent_1 .el-select .el-input .el-select__caret {
    line-height: 0px;
  }
  .voiceAppContent_1 .el-input__inner {
    font-size: 13px;
    height: 6.5vh;
  }
  .voiceAppContent_2 {
    display: flex;
    justify-content: space-between;
  }
  .voiceAppContent_2 > div {
    width: 49%;
    height: 45vh;
    border: 2px solid rgb(24, 228, 240);
    border-radius: 10px;
  }
  .voiceAppContent_2_title {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    background-color: rgb(25, 41, 94);
    height: 4vh;
    line-height: 4vh;
    color: rgb(24, 228, 240);
    display: flex;
    justify-content: space-around;
    font-size: 12px;
  }
  .voiceAppContent_2_content {
    height: 40vh;
    width: 100%;
    overflow-y: auto;
    padding: 0px 10px;
    box-sizing: border-box;
  }
  .voiceAppContent_2_content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .voiceAppContent_2_content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #274088;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  .voiceAppContent_2_content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
  .el-checkbox__label {
    vertical-align: -3px;
  }
  .el-checkbox__label > div {
    display: inline-block;
    color: rgb(24, 228, 240);
    font-size: 13px;
  }
  .el-checkbox {
    display: block;
  }
  .el-checkbox__inner {
    width: 4.5vh;
    height: 4vh;
  }
  .el-checkbox__input {
    vertical-align: bottom;
  }
  .el-checkbox__input .el-checkbox__inner::after {
    border: 2px solid #fff;
    box-sizing: content-box;
    content: "";
    border-left: 0;
    border-top: 0;
    height: 12px;
    width: 5px;
    position: absolute;
    top: -0.5vh;
    left: 1vh;
    transform: rotate(45deg) scaleY(1);
  }
  .voiceAppContent_2_content_selectCar {
    margin-top: 0.5vh;
    color: rgb(24, 228, 240);
    font-size: 13px;
    display: flex;
    justify-content: space-between;
  }
  .voiceAppContent_2_content_selectCar > div {
    height: 6vh;
    line-height: 6vh;
  }
  .voiceAppContent_2_3_content {
    height: 33vh;
    width: 100%;
    overflow-y: auto;
    padding: 0px 10px;
    box-sizing: border-box;
  }
  .voiceAppContent_2_3_content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .voiceAppContent_2_3_content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #274088;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  .voiceAppContent_2_3_content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
  .toCallStyle {
    margin-top: 0.5vh;
    width: 10vw;
    height: 3vh;
    font-size: 12px;
    /* position: absolute;
		left: 50%;
		transform: translateX(-50%); */
  }
  .situationStyle {
    width: 100%;
    height: 17vh;
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;
  }
  .situationStyle::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .situationStyle::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #274088;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  .situationStyle::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
  .situation_fa1 {
    color: #a6f6f9;
    font-size: 12px;
    width: 32%;
    margin: 0px 0.3vh 1vh 0px;
    height: 6vh;
    border: 1px solid rgb(24, 228, 240);
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    cursor: pointer;
    position: relative;
  }
  .situation_fa1 span {
    font-size: 15px;
  }
  .situation_fa2 {
    opacity: 0.8;
    color: #00ffff;
    background-color: #00b6ff;
    font-size: 22px;
    border-radius: 10px;
    margin: 0px 5px 15px;
    width: 32%;
    height: 6vh;
    display: flex;
    align-items: center;
    justify-content: space-around;
    cursor: pointer;
    position: relative;
  }
  .situationNumber {
    padding: 3px;
    color: white;
    box-sizing: border-box;
    border-radius: 50%;
    background-color: #007eff;
    position: absolute;
    right: -10px;
    top: -10px;
    font-size: 18px;
  }
}

@media screen and (min-width: 901px) {
  .tonghuaBtnShow {
    display: none;
  }
  .situationStyle img {
    height: 30px;
  }
  .voiceAppContent_2_content_selectCar_2 {
    width: 27px;
    height: 27px;
    background-color: rgb(4, 112, 171);
    text-align: center;
    font-size: 40px;
  }
  .voiceAppContent_2_content_checkboxs {
    margin-top: 10px;
  }
  .voiceAppContent_1_btn1 {
    width: 6.5vw;
    font-size: 18px;
    height: 6vh;
    text-align: center;
  }
  .voiceAppContent_1_1 {
    font-size: 19px;
    font-weight: 600;
  }
  #audioView {
    position: absolute;
    top: 200px;
    left: 200px;
    z-index: 5;
    background-color: red;
    width: 200px;
    height: 50px;
  }
  .el-input__inner {
    font-size: 18px;
  }
  .voiceAppMainViews {
    position: absolute;
    z-index: 2;
    top: 50%;
    left: 50%;
    height: 85vh;
    width: 60vw;
    background: no-repeat center center
      url("~@/assets/images/truckTuPian/yuyinshenqing1.png");
    background-size: 100% 100%;
    transform: translate(-50%, -50%);
    padding: 12px 30px 0px;
    box-sizing: border-box;
  }
  .voiceAppSmallTitle {
    color: white;
    font-size: 18px;
    text-align: center;
    line-height: 4.5vh;
    width: 9vw;
    height: 4.5vh;
    background: no-repeat center center
      url("~@/assets/images/truckTuPian/xiaobiaotikuang.png");
    background-size: 100% 100%;
  }
  .voiceAppClose {
    position: absolute;
    top: 4vh;
    right: 1vw;
    cursor: pointer;
  }
  .voiceAppContent {
    width: 100%;
  }
  .voiceAppContent > div {
    margin-top: 15px;
  }
  .voiceAppContent_left_title {
    font-size: 21px;
    color: rgb(24, 228, 240);
  }
  .voiceAppContent_1 {
    display: flex;
    justify-content: center;
  }
  .voiceAppContent_1 > div {
    height: 40px;
    line-height: 40px;
    color: rgb(24, 228, 240);
    font-size: 22px;
  }
  .voiceAppContent_2 {
    display: flex;
    justify-content: space-between;
  }
  .voiceAppContent_2 > div {
    width: 49%;
    height: 45vh;
    border: 2px solid rgb(24, 228, 240);
    border-radius: 10px;
  }
  .voiceAppContent_2_title {
    border-radius: 10px;
    background-color: rgb(25, 41, 94);
    height: 4vh;
    line-height: 4vh;
    color: rgb(24, 228, 240);
    display: flex;
    justify-content: space-around;
    font-size: 20px;
  }
  .voiceAppContent_2_content {
    height: 40vh;
    width: 100%;
    overflow-y: auto;
    padding: 0px 10px;
    box-sizing: border-box;
  }
  .voiceAppContent_2_content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .voiceAppContent_2_content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #274088;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  .voiceAppContent_2_content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
  .el-checkbox__label {
    vertical-align: -3px;
  }
  .el-checkbox__label > div {
    display: inline-block;
    color: rgb(24, 228, 240);
    font-size: 20px;
  }
  .el-checkbox {
    display: block;
  }
  .el-checkbox__inner {
    width: 25px;
    height: 25px;
  }
  .el-checkbox__input .el-checkbox__inner::after {
    border: 2px solid #fff;
    box-sizing: content-box;
    content: "";
    border-left: 0;
    border-top: 0;
    height: 12px;
    width: 5px;
    position: absolute;
    top: 1px;
    left: 8px;
    transform: rotate(45deg) scaleY(1);
  }
  .voiceAppContent_2_content_selectCar {
    margin-top: 10px;
    color: rgb(24, 228, 240);
    font-size: 20px;
    display: flex;
    justify-content: space-between;
  }
  .voiceAppContent_2_content_selectCar > div {
    height: 27px;
    line-height: 27px;
  }
  .voiceAppContent_2_3_content {
    height: 33vh;
    width: 100%;
    overflow-y: auto;
    padding: 0px 10px;
    box-sizing: border-box;
  }
  .voiceAppContent_2_3_content::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .voiceAppContent_2_3_content::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #274088;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  .voiceAppContent_2_3_content::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
  .toCallStyle {
    margin-top: 10px;
    width: 130px;
    height: 40px;
    font-size: 18px;
    /* position: absolute;
		left: 50%;
		transform: translateX(-50%); */
  }
  .situationStyle {
    width: 100%;
    height: 15vh;
    display: flex;
    flex-wrap: wrap;
    overflow-y: auto;
  }
  .situationStyle::-webkit-scrollbar {
    /*滚动条整体样式*/
    width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }
  .situationStyle::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 10px;
    background-color: #274088;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.2) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.2) 50%,
      rgba(255, 255, 255, 0.2) 75%,
      transparent 75%,
      transparent
    );
  }
  .situationStyle::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
  .situation_fa1 {
    color: #a6f6f9;
    font-size: 22px;
    margin: 0px 5px 15px;
    width: 32%;
    height: 6vh;
    border: 2px solid rgb(24, 228, 240);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    cursor: pointer;
    position: relative;
  }
  .situation_fa1 span {
    font-size: 30px;
  }
  .situation_fa2 {
    opacity: 0.8;
    color: #00ffff;
    background-color: #00b6ff;
    font-size: 22px;
    border-radius: 10px;
    margin: 0px 5px 15px;
    width: 32%;
    height: 6vh;
    display: flex;
    align-items: center;
    justify-content: space-around;
    cursor: pointer;
    position: relative;
  }
  .situationNumber {
    padding: 3px;
    color: white;
    box-sizing: border-box;
    border-radius: 50%;
    background-color: #007eff;
    position: absolute;
    right: -10px;
    top: -10px;
    font-size: 18px;
  }
}
</style>