前面四章我们搭建一个简单的环境,可以实现在线的音频/视频通讯。接下来,要实现多人的音频/视频通讯。并且利用Android做为客户端。
OpenVidu-Getaroom 是一个在线聊天室的项目,采用原生的js做开发,。
1.启动流媒体服务
docker run -p 4443:4443 --rm -e OPENVIDU_SECRET=MY_SECRET openvidu/openvidu-dev:2.27.0
2.启动getaroom服务端
服务端和第三章的服务一样。
克隆仓库
git clone https://github.com/OpenVidu/openvidu-tutorials.git -b v2.27.0
cd openvidu-tutorials-master/openvidu-basic-node
安装依赖
npm install
启动应用
node index.js
该服务端只有2个函数。
1、创建房间(session)
app.post("/api/sessions", async (req, res) => {
var session = await openvidu.createSession(req.body);
res.send(session.sessionId);
});
由客户端发起请求,服务端转发请求到 流媒体核心服务,以获取房间编号(sessionId)。
2、创建连接(connection)
app.post("/api/sessions/:sessionId/connections", async (req, res) => {
var session = openvidu.activeSessions.find(
(s) => s.sessionId === req.params.sessionId
);
if (!session) {
res.status(404).send();
} else {
var connection = await session.createConnection(req.body);
res.send(connection.token);
}
});
由客户端发起请求,服务端转发请求到 流媒体核心服务,以获取连接编号(Token)。
3.启动getaroom客户端
你需要一个网页的容器,可以使用http-server
npm install -g http-server
把客户端加入到容器中
http-server openvidu-tutorials/openvidu-getaroom/web
访问连接 :http://localhost:8080
接下来看看客户端都干了些什么?
客户端只有4个文件,非常的简单:
openvidu-browser-VERSION.js: openvidu-浏览器js库. 必须要引入该文件。不要尝试去修改,因为完全看不懂。
app.js: 客户端的js,所有的客户端和服务端的交互都在这个文件里面.
index.html: :客户端的html文件,先要引入上面提到的2个js 文件
<script src="openvidu-browser-VERSION.js.js"></script>
<script src="app.js"></script>
style.css:控制样式的css文件
我们来看看app.js中干了写什么?
1.初始化
// Check if the URL already has a room
window.addEventListener('load', function () {
sessionId = window.location.hash.slice(1); // For 'https://myurl/#roomId', sessionId would be 'roomId'
if (sessionId) {
// The URL has a session id. Join the room right away
console.log("Joining to room " + sessionId);
showSessionHideJoin();
joinRoom();
} else {
// The URL has not a session id. Show welcome page
showJoinHideSession();
}
});
// Disconnect participant on browser's window closed
window.addEventListener('beforeunload', function () {
if (session) session.disconnect();
});
当页面加载完毕后,会尝试看看当前输入的连接的sessionId是否还存在,如果在,就申请token并加入房间。如果不在了就把创建房间按钮显示出来。
2. 加入房间
function joinRoom() {
if (!sessionId) {
// If the user is joining to a new room
sessionId = randomString();
}
// --- 1) Get an OpenVidu object ---
OV = new OpenVidu();
// --- 2) Init a session ---
session = OV.initSession();
// --- 3) Specify the actions when events take place in the session ---
// On every new Stream received...
session.on('streamCreated', function (event) {
// Subscribe to the Stream to receive it. HTML video will be appended to element with 'subscriber' id
var subscriber = session.subscribe(event.stream, 'videos');
// When the new video is added to DOM, update the page layout to fit one more participant
subscriber.on('videoElementCreated', function (event) {
numOfVideos++;
updateLayout();
});
});
// On every new Stream destroyed...
session.on('streamDestroyed', function (event) {
// Update the page layout
numOfVideos--;
updateLayout();
});
// On every asynchronous exception...
session.on('exception', (exception) => {
console.warn(exception);
});
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
getToken(sessionId).then(token => {
// Connect with the token
session.connect(token)
.then(() => {
// --- 5) Set page layout for active call ---
// Update the URL shown in the browser's navigation bar to show the session id
var path = (location.pathname.slice(-1) == "/" ? location.pathname : location.pathname + "/");
window.history.pushState("", "", path + '#' + sessionId);
// Auxiliary methods to show the session's view
showSessionHideJoin();
initializeSessionView();
// --- 6) Get your own camera stream with the desired properties ---
publisher = OV.initPublisher('publisher', {
audioSource: undefined, // The source of audio. If undefined default audio input
videoSource: undefined, // The source of video. If undefined default video input
publishAudio: true, // Whether to start publishing with your audio unmuted or not
publishVideo: true, // Whether to start publishing with your video enabled or not
resolution: '640x480', // The resolution of your video
frameRate: 30, // The frame rate of your video
insertMode: 'APPEND', // How the video is inserted in target element 'video-container'
mirror: true // Whether to mirror your local video or not
});
// --- 7) Specify the actions when events take place in our publisher ---
// When our HTML video has been added to DOM...
publisher.on('videoElementCreated', function (event) {
// When your own video is added to DOM, update the page layout to fit it
numOfVideos++;
updateLayout();
$(event.element).prop('muted', true); // Mute local video to avoid feedback
});
// --- 8) Publish your stream ---
session.publish(publisher);
})
.catch(error => {
console.log('There was an error connecting to the session:', error.code, error.message);
});
});
}
加入房间的功能可以分解为两部分,一部分处理自己,另一部分处理其他人。
针对处理自己的逻辑:加入房间后,要做两件事情。
- 推流
- 更新界面,添加一个自己画面的窗口。
针对处理其他人的逻辑:即当其他人加入/离开房间后,要添加/删除用户窗口。