1 创建项目
登录zego控制台,创建一个项目,该项目的【AppId】和【Server】,在后续的推拉流过程中会用到
2 创建对象
// 创建demo节点(拉流remote-preview,推流local-preview)
<div>
<video id='remote-preview' className={cn.remotePreview} autoPlay='autoplay' muted playsInline></video>
<video id='local-preview' className={cn.localPreview} autoPlay='autoplay' muted playsInline></video>
</div>
// 创建zego对象
const appID = xxxxxx // 过程1中的AppId
const server = xxxxxx // 过程1中的Server
const zg = new ZegoExpressEngine(appID, server)
3 定义过程方法
let localStream
// 询问获取设备权限
export const enumDevices = async () => {
try {
const systemInfo = await zg.checkSystemRequirements()
console.log('系统支持信息:', systemInfo)
const deviceInfo = await zg.enumDevices()
console.log('硬件信息:', deviceInfo)
return true
} catch (err) {
console.log('获取设备权限失败:', err)
}
}
// 进房(需要唯一房间id,登录用户id和token)
export const loginRoom = async ({ roomID, userID, token }) => {
try {
const loginStatus = await zg.loginRoom(
roomID,
token,
{
userID: userID,
userName: userID
},
{
userUpdate: true, // 开启监听 roomUserUpdate 回调,默认不开启
}
)
return loginStatus
} catch (err) {
console.log('进房失败:', err)
return false
}
}
// 呼叫推流(需要流id)
export const pushStream = async (streamID) => {
// 调用 createStream 接口后,需要等待 ZEGO 服务器返回流媒体对象才能执行后续操作
localStream = await zg.createStream({
camera: {
audio: true,
video: true,
}
})
// 获取页面的 video 标签
const localVideo = document.getElementById('local-preview')
// stream 为MediaStream对象,开发者可通过赋值给video或audio的srcObject属性进行渲染
localVideo.srcObject = localStream
zg.startPublishingStream(streamID, localStream)
}
// 呼叫拉流(需要流id)
export const pullStream = async (stremID) => {
const remoteStream = await zg.startPlayingStream(stremID)
// 获取页面的 video 标签
const remoteVideo = document.getElementById('remote-preview')
// remoteAudio为本地<video>或<audio>对象
if (remoteVideo) {
remoteVideo.srcObject = remoteStream
}
}
// 停止推流
export const stopPushStream = async (streamID) => {
if (!streamID) return
zg.stopPublishingStream(streamID) // 停止推流
zg.destroyStream(localStream) // 销毁流
localStream = null
}
// 停止拉流
export const stopPullStream = async (streamID) => {
if (!streamID) return
zg.stopPlayingStream(streamID) // 停止拉流
}
// 退出房间
export const logoutRoom = async ({ roomID, psStreamId, plStreamId }) => {
stopPushStream(psStreamId)
stopPullStream(plStreamId)
await zg.logoutRoom(roomID)
}
// 注销监听
export const closeListen = () => {
zg.off('roomUserUpdate')
zg.off('roomOnlineUserCountUpdate')
zg.off('roomStateUpdate')
zg.off('roomStreamUpdate')
zg.off('publisherStateUpdate')
zg.off('publishQualityUpdate')
zg.off('playerStateUpdate')
zg.off('playQualityUpdate')
}
4 实现
登录zego控制台,临时Token 项,点击【临时生成】,弹窗中输入【userID】,点击生成,得到临时【token】。
因为是调试demo,所以这里的【roomID】、【psStreamId】、【plStreeamId】可自定义,例如:0001。
.js
import React, { memo, useEffect } from 'react'
import zg, { loginRoom, enumDevices, pushStream, pullStream, logoutRoom, closeListen } from '过程3文件'
import cn from 'xxx.scss'
const userID = ''
const token = ''
const roomID = '' // 房间id
const psStreamId = '' // 推流id
const plStreamId = '' // 拉流id
function ZegoDemo() {
useEffect(async () => {
initEventRoom()
await loginRoom({ roomID, userID, token }))
return () => {
logoutRoom({ roomID })
closeListen()
}
}, [])
const initEventRoom = () => {
zg.on('roomStateUpdate', (roomID, state, errorCode, extendedData) => {
if (state === 'DISCONNECTED') {
// 与房间断开了连接
console.log(`房间断开连接${roomID}`)
}
if (state === 'CONNECTING') {
// 与房间尝试连接中
console.log(`${roomID}房间连接中。。。。。。。。`)
}
if (state === 'CONNECTED') {
// 与房间连接成功
console.log(`${roomID}房间连接成功`)
// startPush()
// startPull()
}
})
// 用户状态更新回调
zg.on('roomUserUpdate', (roomID, updateType, userList) => {
console.log('用户状态更新回调', roomID, updateType, userList)
})
zg.on('roomOnlineUserCountUpdate', (roomID, count) => {
// 房间人数监听
console.log(`${roomID}房间人数监听:`, count)
})
zg.on('roomStreamUpdate', (roomID, updateType, streamList) => {
console.log('roomStreamUpdate roomID ', roomID, streamList)
})
}
// zego本地推流并进行相关操作
const startPush = async () => {
zg.on('publisherStateUpdate', result => {
// 推流状态更新回调
console.log(`推流结果${result}`)
})
zg.on('publishQualityUpdate', (streamID, stats) => {
// 推流质量回调
console.log(`推流质量:`, stats)
})
// 调用麦克风等权限接口
await enumDevices()
pushStream(psStreamId)
}
const startPull = async () => { // 开始拉流
zg.on('playerStateUpdate', async result => {
// 拉流状态更新回调
console.log(`拉流结果${result}`)
})
zg.on('playQualityUpdate', (streamID, stats) => {
// 拉流质量回调
console.log(`拉流质量:${stats}`)
})
pullStream(plStreamId)
}
const pullStart = async () => { // 开始拉流
startPull()
}
const pullDestory = () => { // 销毁拉流
logoutRoom({ plStreamId })
}
const pushStart = async () => { // 开始推流
startPush()
}
const pushDestory = () => { // 结束推流
logoutRoom({ psStreamId })
}
return <div className={cn.main}>
<div className={cn.line}>
拉流
<div onClick={pullStart}>开始</div>
<div onClick={pullDestory}>销毁</div>
</div>
<video id='remote-preview' className={cn.remotePreview} autoPlay='autoplay' muted playsInline></video>
<div className={cn.line}>
推流
<div onClick={pushStart}>开始</div>
<div onClick={pushDestory}>销毁</div>
</div>
<video id='local-preview' className={cn.localPreview} autoPlay='autoplay' muted playsInline></video>
</div>
}
export default memo(ZegoDemo)