WebSocket+WebRTCwebrtc汇总WebRTC

webrtc实现局域网通话(一)

2019-08-05  本文已影响9人  EarthNut

前言

WebRTC(Web Real-Time Communication)是一个可以用来实现网络实时语音、视频通话的开源项目。

本地视频采集案例

1、建node.js项目

新建文件夹,进入文件夹,新建文件README.md和package.json,打开package.json文件,编写如下内容:

    {
        "name": "communication-demo",
        "version": "0.0.1",
        "description": "A simple demo using webrtc",
        "main": "index.js",
        "author": "wangjie",
        "license": "BSD",
        "private": true,
        "dependencies": {
     
        },
        "scripts": {
            "start": "node index.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 设置成如上图所示即可

上一篇下一篇

猜你喜欢

热点阅读