0%

janus.js video root 基础实例

Janus项目附带实例里有很多业务代码,初学无法抓住重点。
这个例子仅仅包含可以完成一个多人视频会议的最基本的代码。
可查看注释和console输出,快速了解基本流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- index.html -->
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="start">Start</button>
<div id="localVideoWarp">
<div>localVideo</div>
</div>
<div id="remoteVideoWarp">
<div>remoteVideos</div>
</div>

<script type="text/javascript" src="cdnjs/adapter.min.js"></script>
<script type="text/javascript" src="cdnjs/jquery.min.js"></script>
<script type="text/javascript" src="janus.js"></script>
<script type="text/javascript" src="test.js"></script>

</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// test.js

// TODO 服务器已创建好的房间ID
const roomId = 0000;
// 一个随机字符串,可以用来归类来自同一个用户的所有handle
const opaqueId = Janus.randomString(20);
// 本地音视频流
let localStream;
// janus 实例
let janus;
// TODO server地址
const server = 'wss://xxxxx';

// 如果房间配置中require_pvtid===true, 则privateId在订阅流时必须提供该ID
let privateId;
// 发送的远端的字符串,可以传递一些信息,如(用户名,json字符串等)
const display = 'display';
// 用户ID,需保持唯一
const uid = Date.now();

// 本地用户video room handle
let localVideoRoomHandle;
// 远端用户video room handle
const remoteVMHandles = [];

console.log('Janus init start.');
Janus.init({
// debug: 'all',
callback() {
console.log('Janus init success.');

$('#start').click(async () => {
localStream = await navigator.mediaDevices.getUserMedia({audio: true, video: true});
console.log('mediaDevices.getUserMedia success. localStream: ', localStream);
addLocalVideo(localStream);

console.log('Create janus instance start.');
janus = new Janus({
server,
iceServers: [{urls: 'stun:stun.stunprotocol.org'}],
success() {
console.log('Create janus instance success. janus:', janus);

console.log('Attach video room plugin start.');
janus.attach({
plugin: 'janus.plugin.videoroom',
opaqueId,
success(pluginHandle) {
localVideoRoomHandle = pluginHandle;
console.log('Attach video room plugin success. localVideoRoomHandle: ', localVideoRoomHandle);
join();
},
onmessage: function(msg, jsep) {
const event = msg['videoroom'];
switch (event) {
case 'joined': {

const {id, private_id} = msg;
privateId = private_id;
console.log('Join video room success. ', `id: ${id} privateId: ${privateId}`);

// 发布流
publish();

// 如果有远端流。订阅
if (msg['publishers']) {
for (const publisher of msg['publishers']) {
subscribe(publisher.id, publisher.display, publisher.audio, publisher.video);
}
}

break;
}
case 'event': {
// 如果有远端流。订阅
if (msg['publishers']) {
for (const publisher of msg['publishers']) {
subscribe(publisher.id, publisher.display, publisher.audio, publisher.video);
}
}
break;
}

}

// 协商
if (jsep) {
localVideoRoomHandle.handleRemoteJsep({jsep});
}
},
error(err) {
console.error(err);
},
});
},
error(error) {
console.error(error);
},
destroyed() {
console.log('destroyed');
},
});
});
},
});

function join() {
console.log('Join video room start.');
var register = {
request: 'join',
room: roomId,
ptype: 'publisher',
id: uid,
display: display,
};
localVideoRoomHandle.send({message: register});
}

function publish() {
console.log('Publish video room start.');
localVideoRoomHandle.createOffer({
media: {
audioRecv: false,
videoRecv: false,
audioSend: true,
videoSend: true,
},
success(jsep) {
var publish = {request: 'configure', audio: true, video: true};
localVideoRoomHandle.send({message: publish, jsep: jsep});
},
});
}

function subscribe(id, display, audio, video) {
console.log('subscribe start. params:', id, display, audio, video);
let remoteHandle;
janus.attach(
{
plugin: 'janus.plugin.videoroom',
opaqueId,
success: function(pluginHandle) {
remoteHandle = pluginHandle;
const subscribe = {
request: 'join',
room: roomId,
ptype: 'subscriber',
feed: id,
private_id: privateId,
};
remoteHandle.videoCodec = video;
remoteHandle.send({message: subscribe});
console.log('remoteHandle:', remoteHandle);
remoteVMHandles.push(remoteHandle);
},
onmessage(msg, jsep) {
var event = msg['videoroom'];
if (jsep) {
Janus.debug('Handling SDP as well...', jsep);
remoteHandle.createAnswer(
{
jsep: jsep,
media: {audioSend: false, videoSend: false}, // We want recvonly audio/video
success: function(jsep) {
var body = {request: 'start', room: roomId};
remoteHandle.send({message: body, jsep: jsep});
},
});
}
},
onremotestream: function(stream) {
addRemoteVideo(stream, remoteHandle);
},
});
}

function addLocalVideo(stream) {
const videoEle = document.createElement('video');
videoEle.srcObject = stream;
videoEle.width = 320;
videoEle.height = 240;
videoEle.autoplay = true;
$('#localVideoWarp').append(videoEle);
}

function addRemoteVideo(stream, remoteHandle) {

// 同一个远端用户会多次触发onremotestream,需要去重
if ($(`#remoteHandle${remoteHandle.id}`)[0]) {
return;
}

const videoEle = document.createElement('video');
videoEle.srcObject = stream;
videoEle.width = 320;
videoEle.height = 240;
videoEle.autoplay = true;
videoEle.id = `remoteHandle${remoteHandle.id}`;
$('#remoteVideoWarp').append(videoEle);
}