webrtc實現局域網通話(一)

前言

WebRTC(Web Real-Time Communication)是一個可以用來實現網絡實時語音、視頻通話的開源項目。

本地視頻采集案例

1、建node.js項目

新建文件夾,進入文件夾,win10系統在地址欄輸入 cmd 進入命令行,然后輸入 npm init,下面按照提示操作即可創建node.js項目

2、前端代碼

項目目錄下,新建index.html文件,編寫如下內容:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebRTC案例</title>
</head>
<body>
    <div class="container">
        <h1>采集本地視頻</h1>
        <hr>
        <div class="video_container">
             <video id="local_video" autoplay poster="img/video_fill.jpg"></video>
        </div>
        <hr>
        <button type="button" id="start">獲取本地視頻</button>
        <button type="button" id="close">關閉</button>
    </div>
    <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
    <script src="js/main.js"></script>
</body>
</html>

項目目錄下,新建js文件夾,在js文件中新建 main.js 文件,編寫如下代碼:

'use strict'

const loaclVideo = document.getElementById('local_video');
const startButton = document.getElementById('start');
const closeButton = document.getElementById('close');

startButton.addEventListener('click',start);
closeButton.addEventListener('click',close);

closeButton.disabled = true;

var localStream;

function start(){
    navigator.mediaDevices.getUserMedia({audio:false,video:true})
    .then(function(mediaStream){

        startButton.disabled = true;
        closeButton.disabled = false;
        localStream = mediaStream;
        loaclVideo.srcObject = mediaStream;

    }).catch(function(error){
        console.log(JSON.stringify(error));
    });
}

function close(){
    startButton.disabled = false;
    closeButton.disabled = true;
    localStream.getTracks().forEach(track => track.stop());
}

3、服務端代碼

引入 express 框架,在項目文件夾下,鍵入:

npm install express

在項目文件夾下創建index.js文件,編寫如下代碼:

'use strict'

const express = require('express');
const app = express();

app.use('/js',express.static('js'));

app.get('/',function(req,res){
    res.sendFile(__dirname+'/index.html');
});

app.listen(8080);

至此,項目編寫完成

4、測試結果

命令行進入項目文件夾,啟動服務

node index.js

打開瀏覽器,地址欄訪問localhost:8080,效果截圖如下(項目缺少css)

js.png

js2.png

問題總結

如果視頻沒有播放,chrome解決方案是地址欄輸入chrome://flags/,搜索 auto如下圖所示:

js3.png

Autoplay policy 設置成如上圖所示即可

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容