聲網(wǎng)視頻 SDK 被廣泛應(yīng)用于多種實(shí)時(shí)互動(dòng)場景中,例如視頻會(huì)議、視頻通話、音視頻社交、在線教育等。為了讓剛剛接觸聲網(wǎng) SDK 的開發(fā)者,可以更順暢地實(shí)現(xiàn)基礎(chǔ)的視頻通話功能,我們基于聲網(wǎng) Web SDK 4.x 版本梳理了本篇教程。
在本文末,會(huì)提供相應(yīng) Demo 、文檔地址供大家參考使用。同時(shí),歡迎點(diǎn)擊此處注冊聲網(wǎng)賬號(hào)體驗(yàn)。聲網(wǎng)每個(gè)月會(huì)為開發(fā)者提供 10000 分鐘的免費(fèi)額度。
本文為「聲網(wǎng) SDK 教程」系列內(nèi)容
01 Demo 體驗(yàn)
我們在 GitHub 上提供一個(gè)開源的基礎(chǔ)視頻通話示例項(xiàng)目,在開始開發(fā)之前你可以通過該示例項(xiàng)目體驗(yàn)音視頻通話效果。同時(shí),聲網(wǎng)官方還提供了Demo 與線上體驗(yàn)地址。
以下這些資料、文檔,你可能會(huì)在動(dòng)手實(shí)踐過程中會(huì)用到:
1.Github 源碼
https://github.com/AgoraIO/API-Examples-Web/tree/main/Demo/basicVideoCall
2.線上體驗(yàn)Demo(注意,由于體驗(yàn) Demo 需要填寫 appID,所以需要先注冊聲網(wǎng)賬號(hào))
https://webdemo.agora.io/basicVideoCall/index.html
3.注冊聲網(wǎng)賬號(hào)
https://sso2.agora.io/cn/v4/signup/with-sms
4.聲網(wǎng)文檔中心文章來源:http://www.zghlxwxcb.cn/news/detail-406308.html
https://docs.agora.io/cn/Video/downloads?platform=Web文章來源地址http://www.zghlxwxcb.cn/news/detail-406308.html
02 動(dòng)手實(shí)踐
實(shí)踐任務(wù)
從 Web 前端頁面引入聲網(wǎng) SDK,發(fā)起視頻通話。
開發(fā)環(huán)境
聲網(wǎng) SDK 的兼容性良好,對(duì)硬件設(shè)備和軟件系統(tǒng)的要求不高,開發(fā)環(huán)境和測試環(huán)境滿足以下條件即可:
- Chrome
- Firefox
- Safari
- Edge
以下是本文的開發(fā)環(huán)境和測試環(huán)境:
開發(fā)環(huán)境
- MacBook Pro (13-inch, M1, 2020)
- Visual Studio Code (1.67.1)
測試環(huán)境
- Chrome (101.0.4951.64)
如果你此前還未接觸過聲網(wǎng) SDK,那么你還需要做以下準(zhǔn)備工作:
- 注冊一個(gè)聲網(wǎng)賬號(hào),進(jìn)入后臺(tái)創(chuàng)建 AppID、獲取 Token;
- 下載聲網(wǎng)官方最新的 視頻 SDK。
項(xiàng)目設(shè)置
文件組織結(jié)構(gòu)
實(shí)現(xiàn)視頻通話之前,參考如下步驟設(shè)置你的項(xiàng)目:
如需創(chuàng)建新項(xiàng)目,可以在 Visual Studio Code 里 File > New Window,創(chuàng)建 Web 項(xiàng)目。完整的目錄結(jié)構(gòu)如下,根據(jù)個(gè)人經(jīng)驗(yàn)會(huì)有所變化。
.
├── index.css # 用于設(shè)計(jì) Web 應(yīng)用的用戶界面樣式
├── index.html # 用于設(shè)計(jì) Web 應(yīng)用的用戶界面
├── index.js # 通過 AgoraRTCClient 實(shí)現(xiàn)具體應(yīng)用邏輯的代碼。
└── vendor # 第三方前端插件,輔助頁面布局和交互,本教程中是下載到本地使用,你也可以使用 CDN 的方式
├── bootstrap.bundle.min.js
├── bootstrap.min.css
└── jquery-3.4.1.min.js
集成聲網(wǎng) SDK
可以下載到本地使用,也可以直接使用聲網(wǎng)的 CDN 引入, 本文推薦使用 CDN 方式集成聲網(wǎng) SDK。
在 index.html 中添加以下代碼
<!DOCTYPE html>
...
<link rel="stylesheet" href="./vendor/bootstrap.min.css">
<link rel="stylesheet" href="./index.css">
...
<script src="./vendor/jquery-3.4.1.min.js"></script>
<script src="./vendor/bootstrap.bundle.min.js"></script>
<script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>
<script src="./index.js"></script>
...
最終完整代碼為
可以直接復(fù)制運(yùn)行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Basic Video Call -- Agora</title>
<link rel="stylesheet" href="./vendor/bootstrap.min.css">
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="container-fluid banner">
<p class="banner-text">Basic Video Call</p>
<a style="color: rgb(255, 255, 255);fill: rgb(255, 255, 255);fill-rule: evenodd; position: absolute; right: 10px; top: 4px;"
class="Header-link " >
<svg class="octicon octicon-mark-github v-align-middle" height="32" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path></svg>
</a>
</div>
<div id="success-alert" class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Congratulations!</strong><span> You can invite others join this channel by click </span><a href="" target="_blank">here</a>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="success-alert-with-token" class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Congratulations!</strong><span> Joined room successfully. </span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div id="success-alert-with-token" class="alert alert-success alert-dismissible fade show" role="alert">
<strong>Congratulations!</strong><span> Joined room successfully. </span>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="container">
<form id="join-form">
<div class="row join-info-group">
<div class="col-sm">
<p class="join-info-text">AppID</p>
<input id="appid" type="text" placeholder="enter appid" required>
<p class="tips">If you don`t know what is your appid, checkout <a >this</a></p>
</div>
<div class="col-sm">
<p class="join-info-text">Token(optional)</p>
<input id="token" type="text" placeholder="enter token">
<p class="tips">If you don`t know what is your token, checkout <a >this</a></p>
</div>
<div class="col-sm">
<p class="join-info-text">Channel</p>
<input id="channel" type="text" placeholder="enter channel name" required>
<p class="tips">If you don`t know what is your channel, checkout <a >this</a></p>
</div>
</div>
<div class="button-group">
<button id="join" type="submit" class="btn btn-primary btn-sm">Join</button>
<button id="leave" type="button" class="btn btn-primary btn-sm" disabled>Leave</button>
</div>
</form>
<div class="row video-group">
<div class="col">
<p id="local-player-name" class="player-name"></p>
<div id="local-player" class="player"></div>
</div>
<div class="w-100"></div>
<div class="col">
<div id="remote-playerlist"></div>
</div>
</div>
</div>
<script src="./vendor/jquery-3.4.1.min.js"></script>
<script src="./vendor/bootstrap.bundle.min.js"></script>
<script src="https://download.agora.io/sdk/release/AgoraRTC_N.js"></script>
<script src="./index.js"></script>
</body>
</html>
視頻通話邏輯
實(shí)現(xiàn)視頻通話邏輯
下圖展示視頻通話的 API 調(diào)用時(shí)序,注意圖中的方法是對(duì)不同的對(duì)象調(diào)用的。
參考以下步驟實(shí)現(xiàn)音視頻通話的邏輯:
1.調(diào)用 createClient 方法創(chuàng)建 AgoraRTCClient
對(duì)象。
2.調(diào)用 join 方法加入一個(gè) RTC 頻道,你需要在該方法中傳入 App ID 、用戶 ID、Token、頻道名稱。
3.先調(diào)用 createMicrophoneAudioTrack 通過麥克風(fēng)采集的音頻創(chuàng)建本地音頻軌道對(duì)象,調(diào)用 createCameraVideoTrack 通過攝像頭采集的視頻創(chuàng)建本地視頻軌道對(duì)象;然后調(diào)用 publish 方法,將這些本地音視頻軌道對(duì)象當(dāng)作參數(shù)即可將音視頻發(fā)布到頻道中。
4.當(dāng)一個(gè)遠(yuǎn)端用戶加入頻道并發(fā)布音視頻軌道時(shí):
a.監(jiān)聽 client.on(“user-published”) 事件。當(dāng) SDK 觸發(fā)該事件時(shí),在這個(gè)事件回調(diào)函數(shù)的參數(shù)中你可以獲取遠(yuǎn)端用戶 AgoraRTCRemoteUser
對(duì)象 。
b.調(diào)用 subscribe 方法訂閱遠(yuǎn)端用戶 AgoraRTCRemoteUser
對(duì)象,獲取遠(yuǎn)端用戶的遠(yuǎn)端音頻軌道 RemoteAudioTrack
和遠(yuǎn)端視頻軌道 RemoteVideoTrack
對(duì)象。
c.調(diào)用 play
方法播放遠(yuǎn)端音視頻軌道。
注:以下代碼都將在 index.js 中添加**
初始化client
var client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
加入RTC 頻道并創(chuàng)建本地音頻軌道
// Join a channel and create local tracks. Best practice is to use Promise.all and run them concurrently.
[ options.uid, localTracks.audioTrack, localTracks.videoTrack ] = await Promise.all([
// Join the channel.
client.join(options.appid, options.channel, options.token || null, options.uid || null),
// Create tracks to the local microphone and camera.
AgoraRTC.createMicrophoneAudioTrack(),
AgoraRTC.createCameraVideoTrack()
]);
播放本地視頻
// Play the local video track to the local browser and update the UI with the user ID.
localTracks.videoTrack.play("local-player");
發(fā)布本地音視頻到頻道中
// Publish the local video and audio tracks to the channel.
await client.publish(Object.values(localTracks));
監(jiān)聽遠(yuǎn)端用戶音視頻
// Add an event listener to play remote tracks when remote user publishes.
client.on("user-published", handleUserPublished);
client.on("user-unpublished", handleUserUnpublished);
function handleUserPublished(user, mediaType) {
const id = user.uid;
remoteUsers[id] = user;
subscribe(user, mediaType);
}
function handleUserUnpublished(user, mediaType) {
if (mediaType === 'video') {
const id = user.uid;
delete remoteUsers[id];
$(`#player-wrapper-${id}`).remove();
}
}
async function subscribe(user, mediaType) {
const uid = user.uid;
// subscribe to a remote user
await client.subscribe(user, mediaType);
console.log("subscribe success");
if (mediaType === 'video') {
const player = $(`
<div id="player-wrapper-${uid}">
<p class="player-name">remoteUser(${uid})</p>
<div id="player-${uid}" class="player"></div>
</div>
`);
$("#remote-playerlist").append(player);
user.videoTrack.play(`player-${uid}`);
}
if (mediaType === 'audio') {
user.audioTrack.play();
}
}
離開頻道
async function leave() {
for (trackName in localTracks) {
var track = localTracks[trackName];
if(track) {
track.stop();
track.close();
localTracks[trackName] = undefined;
}
}
// Remove remote users and player views.
remoteUsers = {};
$("#remote-playerlist").html("");
// leave the channel
await client.leave();
}
最終完整的代碼
// create Agora client
var client = AgoraRTC.createClient({ mode: "rtc", codec: "vp8" });
var localTracks = {
videoTrack: null,
audioTrack: null
};
var remoteUsers = {};
// Agora client options
var options = {
appid: null,
channel: null,
uid: null,
token: null
};
// the demo can auto join channel with params in url
$(() => {
var urlParams = new URL(location.href).searchParams;
options.appid = urlParams.get("appid");
options.channel = urlParams.get("channel");
options.token = urlParams.get("token");
if (options.appid && options.channel) {
$("#appid").val(options.appid);
$("#token").val(options.token);
$("#channel").val(options.channel);
$("#join-form").submit();
}
})
$("#join-form").submit(async function (e) {
e.preventDefault();
$("#join").attr("disabled", true);
try {
options.appid = $("#appid").val();
options.token = $("#token").val();
options.channel = $("#channel").val();
await join();
if(options.token) {
$("#success-alert-with-token").css("display", "block");
} else {
$("#success-alert a").attr("href", `index.html?appid=${options.appid}&channel=${options.channel}&token=${options.token}`);
$("#success-alert").css("display", "block");
}
} catch (error) {
console.error(error);
} finally {
$("#leave").attr("disabled", false);
}
})
$("#leave").click(function (e) {
leave();
})
async function join() {
// add event listener to play remote tracks when remote user publishs.
client.on("user-published", handleUserPublished);
client.on("user-unpublished", handleUserUnpublished);
// join a channel and create local tracks, we can use Promise.all to run them concurrently
[ options.uid, localTracks.audioTrack, localTracks.videoTrack ] = await Promise.all([
// join the channel
client.join(options.appid, options.channel, options.token || null),
// create local tracks, using microphone and camera
AgoraRTC.createMicrophoneAudioTrack(),
AgoraRTC.createCameraVideoTrack()
]);
// play local video track
localTracks.videoTrack.play("local-player");
$("#local-player-name").text(`localVideo(${options.uid})`);
// publish local tracks to channel
await client.publish(Object.values(localTracks));
console.log("publish success");
}
async function leave() {
for (trackName in localTracks) {
var track = localTracks[trackName];
if(track) {
track.stop();
track.close();
localTracks[trackName] = undefined;
}
}
// remove remote users and player views
remoteUsers = {};
$("#remote-playerlist").html("");
// leave the channel
await client.leave();
$("#local-player-name").text("");
$("#join").attr("disabled", false);
$("#leave").attr("disabled", true);
console.log("client leaves channel success");
}
async function subscribe(user, mediaType) {
const uid = user.uid;
// subscribe to a remote user
await client.subscribe(user, mediaType);
console.log("subscribe success");
if (mediaType === 'video') {
const player = $(`
<div id="player-wrapper-${uid}">
<p class="player-name">remoteUser(${uid})</p>
<div id="player-${uid}" class="player"></div>
</div>
`);
$("#remote-playerlist").append(player);
user.videoTrack.play(`player-${uid}`);
}
if (mediaType === 'audio') {
user.audioTrack.play();
}
}
function handleUserPublished(user, mediaType) {
const id = user.uid;
remoteUsers[id] = user;
subscribe(user, mediaType);
}
function handleUserUnpublished(user) {
const id = user.uid;
delete remoteUsers[id];
$(`#player-wrapper-${id}`).remove();
}
運(yùn)行效果
[外鏈圖片轉(zhuǎn)存失敗,源站可能有防盜鏈機(jī)制,建議將圖片保存下來直接上傳(img-qHpzqvtR-1658572023354)(data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg==)]在瀏覽器開兩個(gè)tab運(yùn)行網(wǎng)頁,使用兩個(gè)用戶加入同一個(gè)頻道,如果能看見兩個(gè)自己,說明你成功了。
03 完整代碼下載
訪問聲網(wǎng)文檔中心,根據(jù)下圖所示路徑,下載對(duì)應(yīng) SDK 壓縮包。壓縮包中包含完整代碼。
參考鏈接
1.Github 源碼
https://github.com/AgoraIO/API-Examples-Web/tree/main/Demo/basicVideoCall
2.線上體驗(yàn)Demo(注意,由于體驗(yàn) Demo 需要填寫 appID,所以需要先注冊聲網(wǎng)賬號(hào))
https://webdemo.agora.io/basicVideoCall/index.html
3.注冊聲網(wǎng)賬號(hào)
https://sso2.agora.io/cn/v4/signup/with-sms
4.聲網(wǎng)文檔中心
https://docs.agora.io/cn/Video/downloads?platform=Web
到了這里,關(guān)于基于 Web SDK 實(shí)現(xiàn)視頻通話場景 | 聲網(wǎng) SDK 教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!