记录一下项目中声网封装

150 阅读3分钟
封装
// 声网
import user from '@/api/user'
import AgoraRTC, { IAgoraRTCClient } from 'agora-rtc-sdk-ng'
export const AGORA_USB_LOCAL = '_usbCamera' // 查看usb摄像头:_usbCamera
export const AGORA_USB_CHECK = '_usbCheck' // usb视频检查:_usbCheck

const LiveTranscoding = {
  videoCodecProfile: 77
}
export class AgoraRtc {
  rtc: any
  options: any
  constructor () {
    this.rtc = {
      client: null, // 用来放置本地客户端
      localAudioTrack: null, // 用来放置本地音频轨道对象
      localVideoTrack: null, // 用来放置本地视频频轨道对象
      role: 'audience' // audience:观众 host主播
    }
    this.options = {
      appId: '94b0b3c96c814ec88aa701cef4cd052b', // 替换成你自己项目的 App ID
      uid: 0,
      channel: 0, // 传入目标频道名。
      token: null, // 如果你的项目开启了 App 证书进行 Token 鉴权,这里填写生成的 Token 值。
      role: 'audience',
      userAudioTrack: [], // 远端用户音频列表
      type: 1 // 1:视频 音频 2:音频 3:视频 4:监控
    }
  }

  async init (role?: string, type?: number) {
    return new Promise<void>((resolve, reject) => {
      if (role) {
        if (role === 'audience' || role === 'host') {
          this.options.role = role
          this.rtc.client = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' })
          this.rtc.client.setClientRole(role).then((res: any) => { // 直播指定角色
          })
          resolve()
        } else {
          reject(new Error('角色只支持audience或host'))
        }
        if (type === 1 || type === 2 || type === 3) {
          this.options.type = type
        } else {
          this.options.type = 1
        }
      } else {
        this.rtc.client = AgoraRTC.createClient({ mode: 'live', codec: 'vp8' })
        resolve()
      }
    })
  }

  async join (channel: number) {
    this.options.userAudioTrack = []
    this.options.channel = channel
    const uid = await this.rtc.client.join(this.options.appId, this.options.channel.toString(), null, null)
    this.options.uid = uid
    this.rtc.client.setLiveTranscoding(LiveTranscoding).then(() => { //
    })
  }

  async created () {
    if (this.options.type === 1) {
      this.rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack() // 通过麦克风采集的音频创建本地音频轨道对象
      this.rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack() // 通过摄像头采集的视频创建本地视频轨道对象
      await this.rtc.client.publish([this.rtc.localAudioTrack, this.rtc.localVideoTrack])
    } else if (this.options.type === 2) {
      this.rtc.localAudioTrack = await AgoraRTC.createMicrophoneAudioTrack() // 通过麦克风采集的音频创建本地音频轨道对象
      await this.rtc.client.publish([this.rtc.localAudioTrack])
    } else if (this.options.type === 3) {
      this.rtc.localVideoTrack = await AgoraRTC.createCameraVideoTrack() // 通过摄像头采集的视频创建本地视频轨道对象
      await this.rtc.client.publish([this.rtc.localVideoTrack])
    }
  }

  subscribe (onSuccess: any) { // 订阅
    this.rtc.client.on('user-published', async (user: any, mediaType: any) => {
      await this.rtc.client.subscribe(user, mediaType)
      if (mediaType === 'video') {
        this.options.userAudioTrack.push(user)
      }
      onSuccess(user, mediaType)
    })
  }

  leaveMonitor (onSuccess: any) { // 离开监听
    /**
     * user 离线的用户信息
     * reason__ Quit:用户调用了 leave 主动离开频道 ServerTimeOut: 因过长时间收不到对方数据包,超时掉线 BecomeAudience: 用户角色从主播切换为观众
     */
    this.rtc.client.on('user-left', async (user: any, reason: string) => {
      if (reason === 'Quit' || reason === 'ServerTimeOut') {
        onSuccess && onSuccess(user)
      }
    })
  }

  getAllChannelMembers (onSuccess: any) { // 获取频道人员信息[{}]
    onSuccess && onSuccess(this.rtc.client.remoteUsers)
  }

  async leave () {
    // 销毁本地音视频轨道。
    if (this.rtc.localAudioTrack) {
      this.rtc.localAudioTrack.close()
    }
    if (this.rtc.localVideoTrack) {
      this.rtc.localVideoTrack.close()
    }
    await this.rtc.client.leave()
  }

  distalAudioVolume (value: number) { // 控制远端音量
    if (this.options.userAudioTrack.length) {
      this.options.userAudioTrack.forEach((item: any) => {
        item.audioTrack.setVolume(value)
      })
    }
  }

  localAudioVolume (value: number) { // 控制本地音量
    // 0: 静音 100: 代表原始音量
    if (!this.rtc.localAudioTrack) return
    this.rtc.localAudioTrack.setVolume(value)
  }

  play () {
    this.rtc.play('agora_remote', (err: any) => {
      if (err && err.status !== 'aborted') {
        // 播放失败,一般为浏览器策略阻止。引导用户用手势触发恢复播放
        // document.querySelector('#agora_remote').onclick = function () {
        //   this.rtc.resume().then((result: any) => {
        //     console.log('恢复成功:' + result)
        //   }).catch((reason: any) => {
        //     console.log('恢复失败:' + reason)
        //   })
        // }
      }
    })
  }
}
使用
initVoid () {
    data.roomNumber = route.query.room
    data.memberName = route.query.memberName
    agoraRtc = new AgoraRtc()
    agoraRtc.init('host', 2).then(() => {
      agoraRtc.leave().then(() => {
        agoraRtc.join(data.roomNumber).then(() => {
          methods.handleMembersLeave()
          agoraRtc.created()
          agoraRtc.subscribe((user: any, mediaType: string) => {
            data.player = true
            if (mediaType === 'video') {
              user.videoTrack.play(document.getElementById('video-container'), { fit: 'contain' })
            }
            if (mediaType === 'audio') {
              user.audioTrack.play()
            }
          })
        })
      })
    })
  },
播放配置
/*Optional
    fit: "cover" | "contain" | "fill" 设置视频播放时的显示模式:
    "cover": 优先保证视窗被填满。视频尺寸等比缩放,直至整个视窗被视频填满
	  "contain": 优先保证视频内容全部显示。视频尺寸等比缩放,直至视频窗口的一边与视窗边框对齐。
    "fill": 保证视窗被填满的同时保证视频内容全部显示,但是不保证视频尺寸比例不变。
  mirror: undefined | false | true
    设置是否开启镜像模式:
     true: 开启镜像模式
     false: 关闭镜像模式

*/
user.videoTrack.play(document.getElementById('video-container'), { fit: 'contain' })