腾讯音视频的使用

 记录一下使用腾讯音视频

安装 trtc

npm install trtc-js-sdk --save

引入 "LibGenerateTestUserSi"文件在阿里云盘里面

import LibGenerateTestUserSig from "@/utils/lib-generate-test-usersig.min.js";
import tRtc from "@/mixins/tRtc";
import TRTC from "trtc-js-sdk";

主体代码 

<template>
  <div class="app-container">
    <el-card>
      <div class="display_flex">
        <div class="callList">
          <el-table
            v-loading="loading"
            :data="tableList"
            @current-change="handleSelectionChange"
            :row-class-name="tableRowClassName"
            max-height="681"
          >
            <el-table-column width="50" align="center" type="index">
              <template slot="header">
                <el-tooltip effect="dark" placement="top-start">
                  <div slot="content">
                    <div>1. 用于接听业主或访客的远程呼叫</div>
                    <div>2. 限集团管理员或物业管理员使用</div>
                  </div>
                  <i
                    class="el-icon-question colorff4949"
                    style="font-size: 16px; margin: 2px -10px 0"
                  ></i>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column
              label="设备编号"
              prop="equipNum"
              align="left"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="设备状态"
              prop="equipStatus"
              align="center"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span
                  :style="
                    scope.row.equipStatus == 1 ? 'color:#262cc6;' : 'color:red;'
                  "
                  >{{ scope.row.equipStatus == 1 ? "在线" : "离线" }}</span
                >
              </template>
            </el-table-column>
            <el-table-column label="时间" align="center" prop="time">
              <template slot-scope="scope">
                <span>{{ $moment(scope.row.time).format("HH:mm:ss") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="呼叫状态" align="center">
              <template slot-scope="scope">
                <span>{{
                  scope.row.state == 0
                    ? "呼叫中"
                    : scope.row.state == 1
                    ? "接听中"
                    : scope.row.state == 2
                    ? "已结束"
                    : "无呼叫"
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button type="primary" @click="openDoor(scope.row)"
                  >开门</el-button
                >
                <el-button
                  type="primary"
                  @click="monitor(scope.$index, scope.row)"
                  v-if="scope.row.equipType == 71"
                  >监控</el-button
                >
                <el-button
                  type="primary"
                  @click="monitor(scope.$index, scope.row)"
                  v-else
                  disabled
                  >监控</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-alert class="alert" v-if="isTip" type="warning">
            <template solt="title">
              <i class="el-icon-phone-outline"></i>
              <span>设备呼叫,请接听</span>
            </template>
          </el-alert>
        </div>
        <div class="wrapper" :class="{ 'is-mobile': $isMobile }">
          <div class="main-window">
            <!-- 远端流区域 -->
            <div
              v-for="item in remoteStreamList"
              :key="item.getUserId()"
              :id="item.getUserId()"
              class="main-window1"
            ></div>
          </div>
          <!-- 本地流区域 -->
          <div v-if="localStream" class="small-video">
            <!-- 本地流播放区域 -->
            <div id="localStream" class="small-video1"></div>
          </div>

          <div v-if="localStream && isPlayingLocalStream">
            <ul class="tab-bar">
              <li
                :class="{ silence: true, isSilence }"
                @click="setOrRelieveSilence"
              ></li>
              <li class="over" @click="handleOver"></li>
              <!-- <li class="remoteOpen" @click="remoteOpen"></li> -->
              <li class="open_door" @click="openDoor()">
                <img src="@/assets/image/wyYunxin/open_door.png" />
              </li>
              <li :class="{ stop: true, isStop }" @click="stopOrOpenVideo"></li>
            </ul>
          </div>
          <div class="videoBg" v-show="!isCalling">
            <div class="videoBg-icon"></div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>
  
<script>
import LibGenerateTestUserSig from "@/utils/lib-generate-test-usersig.min.js";
import {
  findEquipmentWEB,
  remoteDoorOpenAjax,
} from "@/api/communityManage/faceManage/equipManage";
import axios from "axios";
import NERTC from "nertc-web-sdk";
import tRtc from "../_mixins/tRtc.js";
import listMixin from "../_mixins/listMixin";
import TRTC from "trtc-js-sdk";
import { mapGetters, mapState } from "vuex";
export default {
  mixins: [tRtc, listMixin],
  name: "wyYunxin",
  data() {
    return {
      listenIn: {//判断是否是监控视频
        isListenIn: false,
        equipNum: 0,
        index: -1,
      },
      isTip: false,//判断是否有设备被呼叫
      isCall: false,//
      equipId: "",
      isAnswer: false,//判断是否在通话中
      iscolor: "warning-row",//判断来电表格显示的颜色
      callIndex: this.$store.state.app.callIndex,//来电表格的index
      loading: true,
      stepActive: 1,
      userId: undefined,
      roomId: 2043,
      sdkAppId: 1400782381,
      secretKey:
        "4237040c1e77cf62714b7db27b9285129ca9b7178cc10b8235000a0bfa3137dc",
      cameraId: undefined,
      microphoneId: undefined,
      userSig: "",

      isSilence: false,
      isStop: false,
      localUid: Math.ceil(Math.random() * 1e5),
      isCalling: false, //是否接听
      getCallTimeout: null, //获取呼叫定时器
      getMsgTimer: null,
      startCountTimeout: null,
      setTimeoutClose: null,
    };
  },
  created() {
    this.getCallTimeout = setTimeout(() => {
        this.getSystemMsg();
    }, 1500);
  },
  mounted() {
    this.userId = `user_${parseInt(Math.random() * 100000000, 10)}`;
    this.roomId = Number(this.$store.state.app.equipNum);
    navigator.mediaDevices
      .getUserMedia({ audio: true, video: true })
      .then(() => {
        this.getDeviceList(); //调用摄像头和麦克风
      });
    // this.submitForm()
  },
  methods: {
    // 监控视频
    monitor(index, row) {
      this.listenIn.index = index;
      this.listenIn.isListenIn = true;
      this.listenIn.equipNum = row.equipNum;

      let data = new FormData();
      const communityIds = this.communityList
        .map((item) => item.communityId)
        .join(",");
      data.append("communityIds", communityIds);
      data.append("phone", "");
      data.append("reqNo", new Date().getTime());
      data.append("eNum", row.equipNum);
      data.append("optType", 1);
      axios
        .post(
          "https://ai.hbzayun.com/device/scanningTalk/txWp/getSystemMsg",
          data
        )
        .then((res) => {
          console.log(res);
          if (res.data.code == 200 && res.data.data.length > 0) {
            console.log(Number(res.data.data[0].roomNum));
            this.roomId = Number(res.data.data[0].roomNum);
            this.submitForm();
          }
        });
    },
    // 获取设备列表
    getDataListPromise() {
      return findEquipmentWEB({ pn: 1, pageCount: 50, queryType: 4 });
    },
    // 获取麦克风和视频
    async getDeviceList() {
      //调用摄像头麦克风后的操作
      const cameraList = await TRTC.getCameras(); //获取摄像头列表
      const microphoneList = await TRTC.getMicrophones(); //获取麦克风列表
      if (cameraList.length) {
        this.cameraId = cameraList[0].deviceId;
      }
      if (microphoneList.length) {
        this.microphoneId = microphoneList[0].deviceId;
      }
    },
    // 关闭摄像头
    stopOrOpenVideo() {
      const { isStop } = this;
      console.log(isStop);
      this.isStop = !isStop;
      console.log(this.isStop);
      if (this.isStop) {
        console.warn("关闭摄像头");
        this.muteVideo();
      } else {
        console.warn("打开摄像头");
        this.unmuteVideo();
      }
    },
    // 关闭麦克风
    setOrRelieveSilence() {
      const { isSilence } = this;
      console.log(isSilence);
      this.isSilence = !isSilence;
      console.log(this.isSilence);
      if (this.isSilence) {
        this.muteAudio();
      } else {
        this.unmuteAudio();
      }
    },
    // 关闭视频
    async handleOver() {
      if (this.startCountTimeout) {
        clearInterval(this.startCountTimeout);
      }
      await this.leave();
      this.isCall = true;
      this.isTip = false;
      this.$store.commit("app/changeCallIndex", -1);

      let data = new FormData();
      const communityIds = this.communityList
        .map((item) => item.communityId)
        .join(",");
      data.append("communityIds", communityIds);
      data.append("phone", "");
      data.append("reqNo", new Date().getTime());
      if(this.listenIn.isListenIn){
        data.append("eNum", this.listenIn.equipNum);
      }else{
        data.append("eNum", this.tableList[this.callIndex].equipNum);
      }
      data.append("optType", 2);
      
      axios
        .post(
          "https://ai.hbzayun.com/device/scanningTalk/txWp/getSystemMsg",
          data
        )
        .then((res) => {
          console.log(res);
          console.log(111111111111);
        });
      if (this.listenIn.isListenIn) {
        setTimeout(() => {
          this.tableList[this.listenIn.index].state = 2;
          this.iscolor = "";
          this.isCalling = false;
        }, 500);
        setTimeout(() => {
          this.tableList[this.listenIn.index].state = 3;
        }, 3000);
        setTimeout(() => {
          this.listenIn.index = this.$store.state.app.callIndex;
        }, 3100);
      } else {
        setTimeout(() => {
          this.tableList[this.callIndex].state = 2;
          this.iscolor = "";
          this.isCalling = false;
        }, 500);
        setTimeout(() => {
          this.tableList[this.callIndex].state = 3;
        }, 3000);
        setTimeout(() => {
          this.callIndex = this.$store.state.app.callIndex;
        }, 3100);
      }
    },
    //获取呼叫的音视频
    getSystemMsg() {
      clearTimeout(this.getMsgTimer);
      let data = new FormData();
      const communityIds = this.communityList
        .map((item) => item.communityId)
        .join(",");
      data.append("communityIds", communityIds);
      data.append("reqNo", new Date().getTime());
      data.append("optType", 0);
      axios
        .post("https://ai.hbzayun.com/device/scanningTalk/getSystemMsg", data)
        // .post('http://192.168.1.225:9022/device/scanningTalk/getSystemMsg', data)
        .then((res) => {
          if (res.data.code == 200 && res.data.data.length > 0) {
            console.log(res);
            let arr = [];
            this.tableList.forEach((item) => {
              arr.push(item.equipNum);
            });
            let callIndex = arr.findIndex((item) => {
              return item == res.data.data[0].deviceNum;
            });
            this.$store.commit("app/changeCallIndex", callIndex);
            this.callIndex = callIndex;
            this.tableRowClassName({ rowIndex: this.callIndex });
          }
        })
        .finally(() => {
          this.getMsgTimer = setTimeout(() => {
            this.getSystemMsg();
          }, 1500);
        });
    },
    // 点击表格
    handleSelectionChange(selection) {
      if (this.callIndex > -1) {
        if (!this.isAnswer) {
          if (selection.equipNum == this.tableList[this.callIndex].equipNum) {
            this.equipId = selection.equipId;
            this.submitForm();
            this.isCall = false;
            this.iscolor = "success-row";
            this.tableRowClassName({ rowIndex: this.callIndex });
          }
        }
      }
    },
    // 收到消息表格闪动通知
    tableRowClassName({ rowIndex }) {
      if (rowIndex == this.callIndex) {
        if (!this.isCall) {
          this.tableList[this.callIndex].state = 0;
          this.isTip = true;
          console.log(this.isTip);
        }
      }
      console.log(rowIndex, this.callIndex);
      if (rowIndex == this.callIndex) {
        return this.iscolor;
      } else {
        return "";
      }
    },
    // 调用视频通话
    submitForm() {
      console.log(this.cameraId, this.microphoneId);
      if (!this.roomId) {
        return this.msgError("请输入房间号码!");
      }
      if (!this.cameraId || !this.microphoneId) {
        return this.msgError(
          "未获取到相机设备或话筒设备,请检查或刷新页面重新获取!"
        );
      }
      if (this.setTimeoutClose) {
        clearTimeout(this.setTimeoutClose);
      }
      this.isCalling = true;
      if(this.listenIn.isListenIn){
        this.$nextTick(() => {
        this.tableList[this.listenIn.index].state = 1;
      });
      }else{
        this.$nextTick(() => {
        this.tableList[this.callIndex].state = 1;
      });
      }
      
      this.isAnswer = true;
      this.stepActive++;

      this.handleJoinRoom();
    },
    //开门
    openDoor(row) {
      console.log(row);
      this.$confirm(`确认远程开门?`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          if (row) {
            return remoteDoorOpenAjax({ equipId: row.equipId });
          } else {
            return remoteDoorOpenAjax({ equipId: this.equipId });
          }
        })
        .then((res) => {
          if (res.code != 200) {
            this.msgError(`${res.msg}`);
          } else {
            this.msgSuccess(`${res.msg}`);
          }
        })
        .catch(() => {});
    },
    // 点击【Join Room】按钮
    async handleJoinRoom() {
      const userSigGenerator = new LibGenerateTestUserSig(
        this.sdkAppId,
        this.secretKey,
        604800
      );
      this.userSig = userSigGenerator.genTestUserSig(this.userId);

      await this.initClient();
      await this.join();
      await this.initLocalStream();
      await this.playLocalStream();
      await this.publish();
    },

    // 点击【Publish】按钮
    async handlePublish() {
      await this.publish();
    },

    // 点击【Unpublish】按钮
    async handleUnpublish() {
      await this.unPublish();
    },

    // 点击【Leave Room】按钮
    async handleLeave() {
      await this.leave();
      setTimeout(() => {
        this.stepActive--;
      }, 300);
    },

    // 显示成功的 Log
    addSuccessLog(log) {
      console.log(log);
    },
    // 显示失败的 Log
    addFailedLog(log) {
      console.log(log);
    },
    reportSuccessEvent(name) {
      console.log(name);
    },
    reportFailedEvent(name, error, type = "rtc") {
      console.log(name, error, type);
    },
  },
  computed: {
    ...mapState(["app"]),
    ...mapGetters(["userType", "communityList"]),
  },
};
</script>
  
<style scoped lang="scss">
.alert {
  position: absolute;
  height: 35px;
  width: 320px;
  top: 6px;
  left: 10%;
}
::v-deep .el-table::before {
  z-index: 0;
}
.small-video {
  width: 85px;
  height: 115px;
  position: absolute;
  z-index: 9;
  right: 35px;
  top: 16px;
  border: 1px solid #ffffff;
}
.small-video1 {
  height: 100%;
}
.main-window {
  height: 100vh;
  margin: 0 auto;
  background: #25252d;
}
.main-window1 {
  height: 100%;
}
.wrapper {
  height: 80vh;
  position: relative;
  width: calc(100% - 450px);
  background-image: linear-gradient(179deg, #141417 0%, #181824 100%);
  display: flex;
  flex-direction: column;

  .call-detail {
    position: absolute;
    top: 16px;
    left: 16px;
    font-size: 10px;
    line-height: 18px;
    padding: 8px 12px;
    border-radius: 5px;
    background-color: rgba(33, 33, 41, 0.5);
  }
  .call-detail .title {
    color: #bfbfbf;
  }
  .call-detail .text {
    color: #efefef;
  }

  .tab-bar {
    height: 54px;
    background-image: linear-gradient(180deg, #292933 7%, #212129 100%);
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.3);
    list-style: none;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;

    li {
      height: 54px;
      width: 125px;
      cursor: pointer;
      //静音
      &.silence {
        background: url("../../../assets/image/wyYunxin/silence.png") no-repeat
          center;
        background-size: 60px 54px;

        &:hover {
          background: url("../../../assets/image/wyYunxin/silence-hover.png")
            no-repeat center;
          background-size: 60px 54px;
        }

        &:active {
          background: url("../../../assets/image/wyYunxin/silence-click.png")
            no-repeat center;
          background-size: 60px 54px;
        }

        &.isSilence {
          //已经开启静音
          background: url("../../../assets/image/wyYunxin/relieve-silence.png")
            no-repeat center;
          background-size: 60px 54px;

          &:hover {
            background: url("../../../assets/image/wyYunxin/relieve-silence-hover.png")
              no-repeat center;
            background-size: 60px 54px;
          }

          &:active {
            background: url("../../../assets/image/wyYunxin/relieve-silence-click.png")
              no-repeat center;
            background-size: 60px 54px;
          }
        }
      }

      &.open_door {
        display: flex;
        justify-content: center;
        align-items: center;
        > img {
          width: 54px;
          transition: all 0.35s;
        }
        &:active > img {
          transform: scale(0.92);
        }
      }
      //结束按钮
      &.over {
        background: url("../../../assets/image/wyYunxin/over.png") no-repeat
          center;
        background-size: 68px 36px;

        &:hover {
          background: url("../../../assets/image/wyYunxin/over-hover.png")
            no-repeat center;
          background-size: 68px 36px;
        }

        &:active {
          background: url("../../../assets/image/wyYunxin/over-click.png")
            no-repeat center;
          background-size: 68px 36px;
        }
      }

      // 停止按钮
      &.stop {
        background: url("../../../assets/image/wyYunxin/stop.png") no-repeat
          center;
        background-size: 60px 54px;

        &:hover {
          background: url("../../../assets/image/wyYunxin/stop-hover.png")
            no-repeat center;
          background-size: 60px 54px;
        }

        &:active {
          background: url("../../../assets/image/wyYunxin/stop-click.png")
            no-repeat center;
          background-size: 60px 54px;
        }

        //已经是停止状态
        &.isStop {
          background: url("../../../assets/image/wyYunxin/open.png") no-repeat
            center;
          background-size: 60px 54px;

          &:hover {
            background: url("../../../assets/image/wyYunxin/open-hover.png")
              no-repeat center;
            background-size: 60px 54px;
          }

          &:active {
            background: url("../../../assets/image/wyYunxin/open-click.png")
              no-repeat center;
            background-size: 60px 54px;
          }
        }
      }
    }
  }
}

.videoBg {
  width: 100%;
  height: 100%;
  background-image: linear-gradient(179deg, #141417 0%, #181824 100%);
  position: absolute;
  z-index: 99;
  .videoBg-icon {
    width: 100%;
    height: 100%;
    background: url("../../../assets/image/videoBg.png") no-repeat 50%;
    background-size: 68px 56px;
  }
}
.callList {
  width: 650px;
}
.callList /deep/ .warning-row {
  background: #fdf5e6;
}

.callList /deep/ .success-row {
  background: #f0f9eb;
}
::v-deep .el-table {
  overflow: visible;
}
</style>

tRtc.js

/**
 * 音视频通话集成
 */
function isUndefined(value) {
  return value === 'undefined';
}

import TRTC from 'trtc-js-sdk';

export default {
  data() {
    return {
      client: null,
      localStream: null,
      remoteStreamList: [],
      isJoining: false,
      isJoined: false,
      isPublishing: false,
      isPublished: false,
      isMutedVideo: false,
      isMutedAudio: false,
      isPlayingLocalStream: false,
    };
  },

  methods: {
    // 初始化客户端
    async initClient() {
      this.client = TRTC.createClient({
        mode: 'rtc',
        sdkAppId: this.sdkAppId,
        userId: this.userId,
        userSig: this.userSig,
      });
      this.addSuccessLog(`Client [${this.userId}] created.`);
      this.handleClientEvents();
    },

    async initLocalStream() {
      this.localStream = TRTC.createStream({
        audio: true,
        video: true,
        userId: this.userId,
        cameraId: this.cameraId,
        microphoneId: this.microphoneId,
      });
      try {
        await this.localStream.initialize();
        this.addSuccessLog(`LocalStream [${this.userId}] initialized.`);
      } catch (error) {
        this.localStream = null;
        this.addFailedLog(`LocalStream failed to initialize. Error: ${error.message}.`);
        throw error;
      }
    },

    playLocalStream() {
      this.localStream.play('localStream')
        .then(() => {
          this.isPlayingLocalStream = true;
          this.addSuccessLog(`LocalStream [${this.userId}] playing.`);
        })
        .catch((error) => {
          this.addFailedLog(`LocalStream [${this.userId}] failed to play. Error: ${error.message}`);
        });
    },

    destroyLocalStream() {
      this.localStream && this.localStream.stop();
      this.localStream && this.localStream.close();
      this.localStream = null;
      this.isPlayingLocalStream = false;
    },

    playRemoteStream(remoteStream, element) {
      if (remoteStream.getType() === 'main' && remoteStream.getUserId().indexOf('share') >= 0) {
        remoteStream.play(element, { objectFit: 'contain' }).catch();
      } else {
        remoteStream.play(element).catch();
      }
    },

    resumeStream(stream) {
      stream.resume();
    },

    async join() {
      if (this.isJoining || this.isJoined) {
        return;
      }
      this.isJoining = true;
      !this.client && await this.initClient();
      try {
        await this.client.join({ roomId: this.roomId });
        this.isJoining = false;
        this.isJoined = true;

        this.addSuccessLog(`Join room [${this.roomId}] success.`);
        this.reportSuccessEvent('joinRoom');

        this.startGetAudioLevel();
      } catch (error) {
        this.isJoining = false;
        console.error('join room failed', error);
        this.addFailedLog(`Join room ${this.roomId} failed, please check your params. Error: ${error.message}`);
        this.reportFailedEvent('joinRoom', error);
        throw error;
      }
    },

    async publish() {
      if (!this.isJoined || this.isPublishing || this.isPublished) {
        return;
      }
      this.isPublishing = true;
      try {
        await this.client.publish(this.localStream);
        this.isPublishing = false;
        this.isPublished = true;

        this.addSuccessLog('LocalStream is published successfully.');
        this.reportSuccessEvent('publish');
      } catch (error) {
        this.isPublishing = false;
        console.error('publish localStream failed', error);
        this.addFailedLog(`LocalStream is failed to publish. Error: ${error.message}`);
        this.reportFailedEvent('publish');
        throw error;
      }
    },

    async unPublish() {
      if (!this.isPublished || this.isUnPublishing) {
        return;
      }
      this.isUnPublishing = true;
      try {
        await this.client.unpublish(this.localStream);
        this.isUnPublishing = false;
        this.isPublished = false;

        this.addSuccessLog('localStream unpublish successfully.');
        this.reportSuccessEvent('unpublish');
      } catch (error) {
        this.isUnPublishing = false;
        console.error('unpublish localStream failed', error);
        this.addFailedLog(`LocalStream is failed to unpublish. Error: ${error.message}`);
        this.reportFailedEvent('unpublish', error);
        throw error;
      }
    },

    async subscribe(remoteStream, config = { audio: true, video: true }) {
      try {
        await this.client.subscribe(remoteStream, {
          audio: isUndefined(config.audio) ? true : config.audio,
          video: isUndefined(config.video) ? true : config.video,
        });
        this.addSuccessLog(`Subscribe [${remoteStream.getUserId()}] success.`);
        this.reportSuccessEvent('subscribe');
      } catch (error) {
        console.error(`subscribe ${remoteStream.getUserId()} with audio: ${config.audio} video: ${config.video} error`, error);
        this.addFailedLog(`Subscribe ${remoteStream.getUserId()} failed!`);
        this.reportFailedEvent('subscribe', error);
      }
    },

    async unSubscribe(remoteStream) {
      try {
        await this.client.unsubscribe(remoteStream);
        this.addSuccessLog(`unsubscribe [${remoteStream.getUserId()}] success.`);
        this.reportSuccessEvent('unsubscribe');
      } catch (error) {
        console.error(`unsubscribe ${remoteStream.getUserId()} error`, error);
        this.addFailedLog(`unsubscribe ${remoteStream.getUserId()} failed!`);
        this.reportFailedEvent('unsubscribe', error);
      }
    },

    async leave() {
      if (!this.isJoined || this.isLeaving) {
        return;
      }
      this.isLeaving = true;
      this.stopGetAudioLevel();
      this.isPublished && await this.unPublish();
      this.localStream && this.destroyLocalStream();

      try {
        await this.client.leave();
        this.isLeaving = false;
        this.isJoined = false;

        this.addSuccessLog('Leave room success.');
        this.reportSuccessEvent('leaveRoom');
      } catch (error) {
        this.isLeaving = false;
        console.error('leave room error', error);
        this.addFailedLog(`Leave room failed. Error: ${error.message}`);
        this.reportFailedEvent('leaveRoom', error);
        throw error;
      }
    },

    muteVideo() {
      if (this.localStream) {
        this.localStream.muteVideo();
        this.isMutedVideo = true;
        this.addSuccessLog('LocalStream muted video.');
      }
    },

    muteAudio() {
      if (this.localStream) {
        this.localStream.muteAudio();
        this.isMutedAudio = true;
        this.addSuccessLog('LocalStream muted audio.');
      }
    },

    unmuteVideo() {
      if (this.localStream) {
        this.localStream.unmuteVideo();
        this.isMutedVideo = false;
        this.addSuccessLog('LocalStream unmuted video.');
      }
    },

    unmuteAudio() {
      if (this.localStream) {
        this.localStream.unmuteAudio();
        this.isMutedAudio = false;
        this.addSuccessLog('LocalStream unmuted audio.');
      }
    },

    switchDevice(type, deviceId) {
      try {
        if (this.localStream) {
          this.localStream.switchDevice(type, deviceId);
          this.addSuccessLog(`Switch ${type} device success.`);
        }
      } catch (error) {
        console.error('switchDevice failed', error);
        this.addFailedLog(`Switch ${type} device failed.`);
      }
    },

    startGetAudioLevel() {
      // 文档:https://web.sdk.qcloud.com/trtc/webrtc/doc/zh-cn/module-ClientEvent.html#.AUDIO_VOLUME
      this.client.on('audio-volume', (event) => {
        event.result.forEach(({ userId, audioVolume }) => {
          if (audioVolume > 2) {
            console.log(`user: ${userId} is speaking, audioVolume: ${audioVolume}`);
          }
        });
      });
      this.client.enableAudioVolumeEvaluation(200);
    },

    stopGetAudioLevel() {
      this.client && this.client.enableAudioVolumeEvaluation(-1);
    },

    handleClientEvents() {
      this.client.on('error', (error) => {
        console.error(error);
        alert(error);
      });
      this.client.on('client-banned', async (event) => {
        console.warn(`client has been banned for ${event.reason}`);

        this.isPublished = false;
        this.localStream = null;
        await this.leave();
      });
      // fired when a remote peer is joining the room
      this.client.on('peer-join', (event) => {
        const { userId } = event;
        console.log(`peer-join ${userId}`, event);
      });
      // fired when a remote peer is leaving the room
      this.client.on('peer-leave', (event) => {
        const { userId } = event;
        console.log(`peer-leave ${userId}`, event);
      });

      // fired when a remote stream is added
      this.client.on('stream-added', (event) => {
        const { stream: remoteStream } = event;
        const remoteUserId = remoteStream.getUserId();
        if (remoteUserId === `share_${this.userId}`) {
          // don't need screen shared by us
          this.unSubscribe(remoteStream);
        } else {
          console.log(`remote stream added: [${remoteUserId}] type: ${remoteStream.getType()}`);
          // subscribe to this remote stream
          this.subscribe(remoteStream);
          this.addSuccessLog(`RemoteStream added: [${remoteUserId}].`);
        }
      });
      // fired when a remote stream has been subscribed
      this.client.on('stream-subscribed', (event) => {
        const { stream: remoteStream } = event;
        const remoteUserId = remoteStream.getUserId();
        console.log('stream-subscribed userId: ', remoteUserId);
        this.addSuccessLog(`RemoteStream subscribed: [${remoteUserId}].`);
        this.remoteStreamList.push(remoteStream);
        this.$nextTick(() => {
          this.playRemoteStream(remoteStream, remoteUserId);
        });
      });
      // fired when the remote stream is removed, e.g. the remote user called Client.unpublish()
      this.client.on('stream-removed', (event) => {
        const { stream: remoteStream } = event;
        remoteStream.stop();
        const index = this.remoteStreamList.indexOf(remoteStream);
        if (index >= 0) {
          this.remoteStreamList.splice(index, 1);
        }
        console.log(`stream-removed userId: ${remoteStream.getUserId()} type: ${remoteStream.getType()}`);
      });

      this.client.on('stream-updated', (event) => {
        const { stream: remoteStream } = event;
        console.log(`type: ${remoteStream.getType()} stream-updated hasAudio: ${remoteStream.hasAudio()} hasVideo: ${remoteStream.hasVideo()}`);
        this.addSuccessLog(`RemoteStream updated: [${remoteStream.getUserId()}] audio:${remoteStream.hasAudio()}, video:${remoteStream.hasVideo()}.`);
      });

      this.client.on('mute-audio', (event) => {
        const { userId } = event;
        console.log(`${userId} mute audio`);
        this.addSuccessLog(`[${event.userId}] mute audio.`);
      });
      this.client.on('unmute-audio', (event) => {
        const { userId } = event;
        console.log(`${userId} unmute audio`);
        this.addSuccessLog(`[${event.userId}] unmute audio.`);
      });
      this.client.on('mute-video', (event) => {
        const { userId } = event;
        console.log(`${userId} mute video`);
        this.addSuccessLog(`[${event.userId}] mute video.`);
      });
      this.client.on('unmute-video', (event) => {
        const { userId } = event;
        console.log(`${userId} unmute video`);
        this.addSuccessLog(`[${event.userId}] unmute video.`);
      });

      this.client.on('connection-state-changed', (event) => {
        console.log(`RtcClient state changed to ${event.state} from ${event.prevState}`);
      });

      this.client.on('network-quality', (event) => {
        const { uplinkNetworkQuality, downlinkNetworkQuality } = event;
        console.log(`network-quality uplinkNetworkQuality: ${uplinkNetworkQuality}, downlinkNetworkQuality: ${downlinkNetworkQuality}`);
      });
    },
  },
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值