本文介绍如何通过少量代码集成视频 SDK 并调用 API,在你的 Web 应用中实现低延时观众端。
你需要满足以下前提条件:
创建一个名为 agora_web_quickstart
的文件夹。一个 Web 客户端项目至少需包含以下文件:
index.html
: 用于设计 Web 应用的用户界面。basicLiveStreaming.js
: 通过 AgoraRTCClient
实现具体应用逻辑的代码。package.json
: 安装并管理项目依赖。你可以通过命令行进入 agora_web_quickstart
目录并运行 npm init
命令来创建 package.json
文件。下文介绍通过视频 SDK 在你的 Web 应用中实现低延时观众端的详细步骤。
参考以下步骤通过 npm 将声网 Web SDK 集成到你的项目中:
在 package.json
文件的 dependencies
字段中添加 agora-rtc-sdk-ng
及版本号:
{
"name": "agora_web_quickstart",
"version": "1.0.0",
"description": "",
"main": "basicLiveStreaming.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"agora-rtc-sdk-ng": "latest"
},
"author": "",
"license": "ISC"
}
将以下代码复制到 basicLiveStreaming.js
文件中,在你的项目中导入 AgoraRTC
模块。
import AgoraRTC from "agora-rtc-sdk-ng"
将以下代码复制到 index.html
实现客户端用户界面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Video Web SDK Quickstart</title>
<!--
This line is used to refer to the bundle.js file packaged by webpack. A sample webpack configuration is shown in the later step of running your app.
-->
<script src="./dist/bundle.js"></script>
</head>
<body>
<h2 class="left-align">Video Web SDK Quickstart</h2>
<div class="row">
<div>
<button type="button" id="join">Join</button>
<button type="button" id="leave">Leave</button>
</div>
</div>
</body>
</html>
参考以下步骤实现低延时观众端的逻辑:
createClient
方法创建 AgoraRTCClient
对象。setClientRole
方法,将角色 role
设为 "audience"
(观众), 将延时等级 level
设为 1
(低延时)。join
方法加入一个 RTC 频道,你需要在该方法中传入 App ID 、用户 ID、Token、频道名称。client.on("user-published")
事件。当 SDK 触发该事件时,在这个事件回调函数的参数中你可以获取远端用户 AgoraRTCRemoteUser
对象 。subscribe
方法订阅远端用户 AgoraRTCRemoteUser
对象,获取远端用户的远端音频轨道 RemoteAudioTrack
和远端视频轨道 RemoteVideoTrack
对象。play
方法播放远端音视频轨道。下图展示了基础的音视频直播的 API 调用。注意图中的方法是对不同的对象调用的。
将以下代码复制到 basicLiveStreaming.js
文件中,注意将 appID
和 token
替换为你自己的 App ID 和临时 Token。
import AgoraRTC from "agora-rtc-sdk-ng"
let rtc = {
// For the local audio and video tracks.
localAudioTrack: null,
localVideoTrack: null,
client: null
};
let options = {
// Pass your app ID here.
appId: "your_app_id",
// Set the channel name.
channel: "test",
// Set the user role in the channel.
role: "audience",
// Use a temp token
token: "your_temp_token",
// Uid
uid: 123456
};
let clientRoleOptions = {
// Set latency level to low latency
level: 1
}
async function startBasicLiveStreaming() {
rtc.client = AgoraRTC.createClient({ mode: "live", codec: "vp8" });
window.onload = function () {
document.getElementById("join").onclick = async function () {
rtc.client.setClientRole(options.role, clientRoleOptions);
await rtc.client.join(options.appId, options.channel, options.token, options.uid);
}
document.getElementById("leave").onclick = async function () {
// Traverse all remote users.
rtc.client.remoteUsers.forEach(user => {
// Destroy the dynamically created DIV containers.
const playerContainer = document.getElementById(user.uid);
playerContainer && playerContainer.remove();
});
// Leave the channel.
await rtc.client.leave();
}
}
rtc.client.on("user-published", async (user, mediaType) => {
// Subscribe to a remote user.
await rtc.client.subscribe(user, mediaType);
console.log("subscribe success");
// If the subscribed track is video.
if (mediaType === "video") {
// Get `RemoteVideoTrack` in the `user` object.
const remoteVideoTrack = user.videoTrack;
// Dynamically create a container in the form of a DIV element for playing the remote video track.
const remotePlayerContainer = document.createElement("div");
// Specify the ID of the DIV container. You can use the `uid` of the remote user.
remotePlayerContainer.id = user.uid.toString();
remotePlayerContainer.textContent = "Remote user " + user.uid.toString();
remotePlayerContainer.style.width = "640px";
remotePlayerContainer.style.height = "480px";
document.body.append(remotePlayerContainer);
// Play the remote video track.
// Pass the DIV container and the SDK dynamically creates a player in the container for playing the remote video track.
remoteVideoTrack.play(remotePlayerContainer);
}
// If the subscribed track is audio.
if (mediaType === "audio") {
// Get `RemoteAudioTrack` in the `user` object.
const remoteAudioTrack = user.audioTrack;
// Play the audio track. No need to pass any DOM element.
remoteAudioTrack.play();
}
});
rtc.client.on("user-unpublished", user => {
// Get the dynamically created DIV container.
const remotePlayerContainer = document.getElementById(user.uid);
// Destroy the container.
remotePlayerContainer.remove();
});
}
startBasicLiveStreaming()
本文使用 webpack 打包项目,使用 webpack-dev-server
运行项目。
在 package.json
的 dependencies
中添加 webpack-cli
和 webpack-dev-server
字段中,在 scripts
字段中添加 build
和 start:dev
字段。
{
"name": "agora_web_quickstart",
"version": "1.0.0",
"description": "",
"main": "basicLiveStreaming.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config webpack.config.js",
"start:dev": "webpack serve --open --config webpack.config.js"
},
"dependencies": {
"agora-rtc-sdk-ng": "latest",
"webpack": "5.28.0",
"webpack-dev-server": "3.11.2",
"webpack-cli": "4.10.0"
},
"author": "",
"license": "ISC"
}
在项目目录中创建一个名为 webpack.config.js
的文件,将以下代码复制到 webpack.config.js
配置 webpack:
const path = require("path");
module.exports = {
entry: "./basicLiveStreaming.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "./dist"),
},
devServer: {
compress: true,
port: 9000,
},
};
运行下列命令安装依赖:
npm install
运行下列命令通过 webpack 编译项目:
# Use webpack to package the project
npm run build
通过 webpack-dev-server 运行项目:
npm run start:dev
你的浏览器会自动打开以下页面:
点击 JOIN 加入频道。你还可以邀请朋友克隆 https://github.com/AgoraIO/API-Examples-Web 项目到本地,在浏览器中打开 Demo/index.html
文件,并输入相同的 App ID、频道名称和临时 Token。你的朋友以主播角色加入频道后,你们可以看到彼此,并听到彼此的声音;你的朋友以观众角色加入频道后,你们可以听到彼此的声音。
为保障通信安全,在正式生产环境中,你需要在自己的 app 服务端生成 Token。详见使用 Token 鉴权。
声网在 GitHub 上提供一个开源的示例项目供你参考。
除上文介绍的使用 npm 获取 Web SDK 之外,你还可以使用以下方法获取 SDK:
在项目 HTML 文件中,添加如下代码,使用 CDN 方法获取 SDK:
<script src="https://download.agora.io/sdk/release/AgoraRTC_N-4.18.3.js"></script>
下载声网 Web SDK 4.x 版本 SDK 包至本地,将 SDK 包中的 .js
文件保存到项目文件所在的目录下,然后在项目 HTML 文件中添加如下代码:
<script src="./AgoraRTC_N-4.18.3.js"></script>
AgoraRTC
对象,直接访问这个对象即可操作 SDK。1. 为什么在本地运行快速开始项目时会报错 digital envelope routines::unsupported
?
本文中的快速开始项目通过 webpack 打包并在本地运行。由于 Node.js 16 及以上版本更改了对 OpenSSL 的依赖(详见 node issue),影响了项目中本地开发环境的依赖(详见 webpack issue ),运行项目会发生错误。解决方案如下:
export NODE_OPTIONS=--openssl-legacy-provider
然后再次尝试运行项目。