Bootstrap

web简易视频聊天室+媒体流插入

语音聊天室是最近非常热门的一款语音类软件,但是编写一个语音聊天室软件是不是很困难呢?没关系,今天为大家带来简易版的,非常简单呦!但是光聊天怎么行,想不想一起在聊天室看视频,一起吐槽、观看呢!不要急哟,马上带你们一起写。

一、项目准备

需求:web端的多人视频聊天

用到的技术:

需要使用的RTC - SDK功能

  • 创建RTC音视频引擎:

  • 创建本地音频视频:

  • 加入频道:

  • 离开频道:

  • 开启本地视频发送:

  • 关闭本地视频发送:

  • 订阅拉流:

  • 取消订阅:

  • 添加媒体流:addInjectStreamUrl

  • 删除媒体流:removeInjectStreamUrl

二、项目开发以及相关js代码

下载或引入 anyRTC

  • script导入

使用  标签引入 SDK 时,产生名为 的全局变量,该变量含有该模块的所有成员。

 //引入RTC
复制代码
  • npm 导入

npm install --save ar-rtc-sdk;
import ArRTC from "ar-rtc-sdk"; //导入RTC项目
复制代码

加入同一个房间(join)

html 视频容器


复制代码

相关JS(加入房间并渲染自己视图)

//创建本地视图
const localplayer = $(
`
   

` ); $("#remote-playerlist").append(localplayer); // create ArRTC client client = await ArRTC.createClient({ mode: "rtc", codec: "h264" }); // add event listener to play remote tracks when remote user publishs. client.on("user-published", handleUserPublished); client.on("user-unpublished", handleUserUnpublished); //当前输入媒体流的状态。 client.on("stream-inject-status", handleInjectStatus); // 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, options.uid || null), // create local tracks, using microphone and camera ArRTC.createMicrophoneAudioTrack(), ArRTC.createCameraVideoTrack() ]); localTracks.videoTrack.play("local-player"); 复制代码

相关事件回调(anyrtc sdk配套的事件回调)

用户加入房间(user-published)

function handleUserPublished(user, mediaType) {
	const id = user.uid;
	remoteUsers[id] = user;//存放用户相关视频信息
	subscribe(user, mediaType);//订阅用户发布的视频流
}
复制代码

用户离开房间(user-unpublished)

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 = $(
`
      

remoteUser(${uid})

` ); $("#remote-playerlist").append(player); user.videoTrack.play(`player-${uid}`); } if (mediaType === "audio") { user.audioTrack.play(); } } 复制代码

离开房间(leave)

client.leave();
复制代码

插入媒体流

媒体流地址(html 输入)


复制代码

添加媒体流(addInjectStreamUrl)

// 地址
$("#url").val() ? options.url = $("#url").val() : options.url = $("#url")[0].placeholder;
const injectStreamConfig = {
	width: 0,
	height: 0,
	videoGop: 30,
	videoFramerate: 100,
	videoBitrate: 3500,
	audioSampleRate: 44100,
	audioChannels: 1,
};
await client.addInjectStreamUrl(options.url, injectStreamConfig);
复制代码

停止媒体流(removeInjectStreamUrl)

await client.removeInjectStreamUrl();
复制代码

三、参考

参考  ArRTC WebSDK Demos

作者:anyRTC 张耀