// ArRTC client
var client;
// 存放音视频
var localTracks = {
videoTrack: null,
audioTrack: null,
};
// 存放频道用户
var remoteUsers = {};
// ArRTC client options
var options = {
appid: null,
channel: null,
uid: null,
};
// 查看 SDK 版本
console.log(ArRTC.VERSION);
// 检测麦克风
const Cameras = await ArRTC.getCameras();
// 检测摄像头
const Microphones = await ArRTC.getMicrophones();
if (Cameras.length || Microphones.length) {
options.appid = $("#appid").val();
options.channel = $("#channel").val();
options.uid = $("#uid").val();
// 加入频道
join();
}
async function join() {
//创建本地视图
const localplayer = $(
`
<div class="col-6" id="local_video">
<p id="local-player-name" class="player-name"></p>
<div class="player-with-stats">
<div id="local-player" class="player"></div>
<div id="local-stats" class="stream-stats stats"></div>
</div>
</div>
`
);
$("#remote-playerlist").append(localplayer);
// create ArRTC client
client = await ArRTC.createClient({
mode: "rtc",
codec: "h264",
});
// 用户发布
client.on("user-published", handleUserPublished);
// 用户停止发布
client.on("user-unpublished", handleUserUnpublished);
[
options.uid,
localTracks.audioTrack,
localTracks.videoTrack,
] = await Promise.all([
// join the channel
client.join(
options.appid,
options.channel,
null,
options.uid || null
),
// create local tracks, using microphone and camera
ArRTC.createMicrophoneAudioTrack(),
ArRTC.createCameraVideoTrack(),
]);
// play local video track
localTracks.videoTrack.play("local-player");
$("#local-player-name").text(`localVideo(${options.uid})`);
// 发布本地视频
client.publish(Object.values(localTracks));
}
// 远端用户发布
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();
}
// 订阅远端用户发布的音视频
async function subscribe(user, mediaType) {
const uid = user.uid;
// subscribe to a remote user
await client.subscribe(user, mediaType);
if (mediaType === "video") {
const player = $(
`
<div id="player-wrapper-${uid}" class="col-6">
<p class="player-name">remoteUser(${uid})</p>
<div class="player-with-stats">
<div id="player-${uid}" class="player"></div>
<div class="track-stats stats"></div>
</div>
</div>
`
);
$("#remote-playerlist").append(player);
user.videoTrack.play(`player-${uid}`);
}
if (mediaType === "audio") {
user.audioTrack.play();
}
}
评论