前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >vue使用TRTC Web SDK实现多人会话场景

vue使用TRTC Web SDK实现多人会话场景

原创
作者头像
yuliang
修改2021-03-03 17:58:18
2.5K0
修改2021-03-03 17:58:18
举报
文章被收录于专栏:TRTC Web SDKTRTC Web SDK

基本的对话场景请参考 使用TRTC Web SDK实现实时音视频通话 。本文主要讲述 vue 使用 TRTC Web SDK 来实现多人会议的功能,废话不多说直接上代码:(注意下方代码中 sdkAppId 请使用自己的

代码语言:javascript
复制
<template>
  <div class="win">
    <!-- 收集一些参数,roomId:房间号,userId:用户名称 -->
    <div class="form">
      roomId:<input type="text" v-model="roomId" /> userId:<input
        type="text"
        v-model="userId"
      />
      <button @click="joinroom">加入</button>
      <button @click="leaveroom">挂断</button>
    </div>

    <!-- 用于播放自己的本地流 -->
    <div class="trtc-div" id="mine"></div>

    <!-- 远端流列表 -->
    <div
      v-for="item in remoteStream"
      :key="item.getUserId()"
      :id="item.getUserId()"
      v-on:load="remoteStreamPlay()"
      class="trtc-div"
    ></div>
  </div>
</template>
<style scoped>
.win {
  width: 100%;
  height: 100%;
  border: 1px solid black;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  overflow-y: auto;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-content: flex-start;
}
.form {
  height: 30px;
  width: 100%;
}
.trtc-div {
  height: 200px;
  width: 200px;
  border: 1px solid black;
}
</style>
<script>
// 集成TRTC Web SDK,相关操作请参考:https://cloud.tencent.com/document/product/647/16863
import TRTC from "trtc-js-sdk";
// 用于获取userSig的方法,这里我将生成方式封装成一个方法,文章最后会给出代码和连接,
// 相关操作请参考:UserSig相关问题 https://cloud.tencent.com/document/product/647/17275
import { genTestUserSig } from "../util/GenerateTestUserSig";
export default {
  data() {
    return {
      localStream: null,
      roomId: "",
      userId: "",
      remoteStream: [],
      sdkAppId: 0 // 请填自己的sdkAppId,
      // 了解更多请参考:https://cloud.tencent.com/document/product/647/32398
    };
  },
  methods: {
    // 加入房间
    joinroom() {
      if (this.roomId == "" || this.userId == "" || this.localStream != null) {
        console.log("表单不能为空");
      } else {
        // 判断加入参数填写完全后执行一下代码
        let sdkAppId = this.sdkAppId;
        let userId = this.userId;
        let roomId = this.roomId;
        let client = this.client;
        let localStream = this.localStream;
        let userSig = genTestUserSig(userId).userSig; // 获取userSig
        let clientConfig = {
          mode: "rtc", // 会话模式为rtc实时音视频通话模式
          sdkAppId,
          userId,
          userSig
        };
        client = TRTC.createClient(clientConfig); // 创建一个用户对象
        this.client = client;
        // 添加监听回调函数,当远端流加入时调用
        client.on("stream-added", event => {
          // 判断此远端流用户是否是反复加入的用户
          let index = this.isremoteStream(event.stream.getUserId());
          if (index != -1) {
            // 对反复加入聊天的用户,将原来该用户的视频流替换为新的视频流
            this.unsubscribe[index].stop();
            client.unsubscribe(this.remoteStream[index]);

            this.remoteStream[index] = event.stream;

            client.subscribe(this.remoteStream[index]);
            event.stream.play(event.stream.getUserId());
          } else {
            this.remoteStream.push(event.stream);
            client.subscribe(event.stream);
            this.$nextTick(() => {
              // 列表渲染完成后将新加的远端流进行播放
              event.stream.play(event.stream.getUserId());
            });
          }
        });

        // 监听远端流退出的处理函数,将其从远端流数组中删除
        client.on("stream-removed", event => {
          let index = this.isremoteStream(event.stream.getUserId());
          this.remoteStream[index].stop();
          this.remoteStream.splice(index, 1);
        });

        // 加入房间
        client.join({ roomId: parseInt(roomId) }).then(() => {
          let streamConfig = {
            userId: userId,
            video: true,
            audio: true
          };
          
          localStream = TRTC.createStream(streamConfig); // 创建一个本地流
          localStream.initialize().then(() => {
            // 初始化本地流

            client.publish(localStream); // 初始化完成后进行推流操作
            localStream.play("mine", {
              // 本机播放自己的本地流

              objectFit: "contain",
              muted: true
            });
            this.localStream = localStream;
            this.client = client;
          });
        });
      }
    },

    // 断开房间
    leaveroom() {
      this.client.unpublish(this.localStream).then(() => {
        // 先断开推流,然后完成后续操作
        // 断开后远端的订阅会自动断开不需要手动调用unsubscribe方法,同时远端会触发stream-removed的监听回调

        this.client.leave(); // 离开房间,注意本地端也会触发stream-removed的监听回调
        this.localStream.stop(); // 停止本地的播放
        this.localStream.close(); // 关闭本地流,关闭音频和视频的采集
        this.localStream = null; // 初始状态
      });
    },

    // 判断是否是已加入的远端流,这里我直接使用流的userId进行判断,可以更具需要自行设计,也可配合后端进行判断
    // 没有在房间返回-1,有则返回远端流在数组中的下标
    isremoteStream(userId) {
      let remoteStream = this.remoteStream;
      for (var i = 0; i < remoteStream.length; i++) {
        if (remoteStream[i].getUserId() == userId) return i;
      }
      return -1;
    }
  }
};
</script>

UserSig生成方式:

GenerateTestUserSig.js文件:(注意:其中 SDKAPPID SECRETKEY 请使用自己的

至于 lib-generate-test-usersig.min.js 文件我是在官方提供Demo中找到的下载浏览器的官方Demo可以在

TRTCScenesDemo\trtc-calling-web\public\debug

TRTCSimpleDemo\js

目录下都可以找到

代码语言:javascript
复制
import * as LibGenerateTestUserSig from './lib-generate-test-usersig.min.js'

/**
 * 腾讯云 SDKAppId,需要替换为您自己账号下的 SDKAppId。
 *
 * 进入腾讯云实时音视频[控制台](https://console.cloud.tencent.com/rav ) 创建应用,即可看到 SDKAppId,
 * 它是腾讯云用于区分客户的唯一标识。
 */
const SDKAPPID = 0 // 请根据提示注册腾讯云获取自己的SDKAPPID

/**
 * 签名过期时间,建议不要设置的过短
 * <p>
 * 时间单位:秒
 * 默认时间:7 x 24 x 60 x 60 = 604800 = 7 天
 */
const EXPIRETIME = 604800


/**
 * 计算签名用的加密密钥,获取步骤如下:
 *
 * step1. 进入腾讯云实时音视频[控制台](https://console.cloud.tencent.com/rav ),如果还没有应用就创建一个,
 * step2. 单击“应用配置”进入基础配置页面,并进一步找到“帐号体系集成”部分。
 * step3. 点击“查看密钥”按钮,就可以看到计算 UserSig 使用的加密的密钥了,请将其拷贝并复制到如下的变量中
 *
 * 注意:该方案仅适用于调试Demo,正式上线前请将 UserSig 计算代码和密钥迁移到您的后台服务器上,以避免加密密钥泄露导致的流量盗用。
 * 文档:https://cloud.tencent.com/document/product/647/17275#Server
 */
const SECRETKEY = '' // 请根据提示获取自己的SECRETKEY
/*
 * Module:   GenerateTestUserSig
 *
 * Function: 用于生成测试用的 UserSig,UserSig 是腾讯云为其云服务设计的一种安全保护签名。
 *           其计算方法是对 SDKAppID、UserID 和 EXPIRETIME 进行加密,加密算法为 HMAC-SHA256。
 *
 * Attention: 请不要将如下代码发布到您的线上正式版本的 App 中,原因如下:
 *
 *            本文件中的代码虽然能够正确计算出 UserSig,但仅适合快速调通 SDK 的基本功能,不适合线上产品,
 *            这是因为客户端代码中的 SECRETKEY 很容易被反编译逆向破解,尤其是 Web 端的代码被破解的难度几乎为零。
 *            一旦您的密钥泄露,攻击者就可以计算出正确的 UserSig 来盗用您的腾讯云流量。
 *
 *            正确的做法是将 UserSig 的计算代码和加密密钥放在您的业务服务器上,然后由 App 按需向您的服务器获取实时算出的 UserSig。
 *            由于破解服务器的成本要高于破解客户端 App,所以服务器计算的方案能够更好地保护您的加密密钥。
 *
 * Reference:https://cloud.tencent.com/document/product/647/17275#Server
 */
export function genTestUserSig(userID) {
  const generator = new LibGenerateTestUserSig(SDKAPPID, SECRETKEY, EXPIRETIME)
  const userSig = generator.genTestUserSig(userID)

  return {
    sdkAppID: SDKAPPID,
    userSig: userSig,
  }
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
实时音视频
实时音视频(Tencent RTC)基于腾讯21年来在网络与音视频技术上的深度积累,以多人音视频通话和低延时互动直播两大场景化方案,通过腾讯云服务向开发者开放,致力于帮助开发者快速搭建低成本、低延时、高品质的音视频互动解决方案。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档