• WebRTC音视频数据采集
     var constraints={video: true,audio: true,}navigator.mediaDevices.getUserMedia(constraints).then(gotMediaStream).then(gotDevices).catch(handleError)
function gotMediaStream(stream){videoplay.srcObject=stream;
}

音视频数据采集主要使用getUserMedia方法获取媒体数据,constraints配置采集轨道的参数,video,audio的true表示采集,false表示不采集,然后将数据流通过gotMediaStream方法添加到视频组建上。

  • WebRTC_API_适配
 <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>

添加官方的adapter-latest支持即可

  • 获取音视频设备的访问权限
function gotMediaStream(stream){videoplay.srcObject=stream;return navigator.mediaDevices.enumerateDevices();
}
function gotDevices(deviceInfos){deviceInfos.forEach(function(deviceinfo){var option=   document.createElement('option');option.text=deviceinfo.label;option.value=deviceinfo.deviceId;if(deviceinfo.kind==='audioinput'){audioSource.appendChild(option);}else if(deviceinfo.kind==='audiooutput'){audioOutput.appendChild(option);}else if(deviceinfo.kind==='videoinput'){videoSource.appendChild(option);}})
}

在gotMediaStream方法返回return navigator.mediaDevices.enumerateDevices(),这时gotDevices方法中就可以获取音视频设备

  • 视频约束
     var constraints={video: {width:640,height:480,frameRate:30,//environment:后置摄像头,user:前置摄像头facingMode:"user",deviceId: {exact:deviceId ? deviceId:undefined}},

视频约束所有的配置都在constraints中进行配置,更多详细可以查看官方api

  • 音频约束
 var constraints={video: {width:640,height:480,frameRate:30,//environment:后置摄像头,user:前置摄像头facingMode:"user",deviceId: {exact:deviceId ? deviceId:undefined}},audio: {//降噪noiseSuppression:true,//回音消除echoCancellation:true},}

音频约束和视频约束一样,在constraints中进行配置,更多详细可以查看官方api

  • 视屏特效
     <div><label>Filter:</label><select id="filter"><option value="none">None</option><option value="blur">blur</option><option value="grayscale">Grayscale</option><option value="invert">Invert</option><option value="sepia">sepia</option></select></div>
//特效
filtersSelect.onchange = function(){videoplay.className=filtersSelect.value;
}

设置特效直接设置视频源video的className即可

  • 从视频中获取图片
<!--从视频中获取图片-->
<div><button id="snapshot">Take snapshot</button>
</div><div><canvas id="picture"></canvas>
</div>
//从视频中获取图片
var snapshot =document.querySelector("button#snapshot");
var picture =document.querySelector("canvas#picture");
picture.width=480;
picture.height=640;//从视频中获取图片
snapshot.onclick=function(){picture.className=filtersSelect.valuepicture.getContext('2d').drawImage(videoplay,0,0,picture.width,picture.height);}

从视频中获取图片主要使用的是canvas来绘制的

  • MediaStreamAPI及获取视频约束
//获取屏幕约束
var divConstraints = document.querySelector('div#constraints')function gotMediaStream(stream){var videoTrack = stream.getVideoTracks()[0];var videoConstraints =   videoTrack.getSettings();divConstraints.textContent=   JSON.stringify(videoConstraints,null,2);videoplay.srcObject=stream;return navigator.mediaDevices.enumerateDevices();
}

结果


{ "aspectRatio": 1.3333333333333333, "deviceId": "97953df027728ab0acac98c670d59f654a1e7f36f9faf70f2e0fd7a479394fe3",
"frameRate": 29.969999313354492, "groupId": "1b83734781c08e3c51519598002aa1d5acb1bcd73772f5d2db4b976586af3666",
"height": 480, "width": 640, "videoKind": "color" }

获取视频约束,在gotMediaStream方法中获取视频轨道,信息都在轨道中获取

  • 录制音频视屏
//视频录制
btnRecord.onclick=()=>{if(btnRecord.textContent==='Start Record'){startRecord();btnRecord.textContent='Stop Record'btnPlay.disabled=true;btnDownload.disabled=true;}else{stopRecord();btnRecord.textContent='Start Record'btnPlay.disabled=false;btnDownload.disabled=false;}
}
function gotMediaStream(stream){...window.stream=stream;...return navigator.mediaDevices.enumerateDevices();
}
//开始录制
function startRecord(){buffer=[];var options={mimeType: 'video/webm;codecs=vp8'}if(!window.MediaRecorder.isTypeSupported(options.mimeType)){console.error('${options.mimeType} is not supported');return;}try {mediaRecorder= new window.MediaRecorder(window.stream,options);} catch (e) {console.error('failed to create  MediaRecorder:',e);return;}mediaRecorder.ondataavailable= handleDataAvailable;mediaRecorder.start(10);
}//停止录制function stopRecord(){mediaRecorder.stop();
}
  • 播放录制视频
btnPlay.onclick=()=>{var blob =new Blob(buffer,{type: 'video/webm'});recvideo.src=window.URL.createObjectURL(blob);recvideo.srcObject=null;recvideo.controls=true;recvideo.play();
}
  • 下载录制视频
btnDownload.onclick=()=>{var blob =new Blob(buffer,{type:'video/webm'});var url = window.URL.createObjectURL(blob);var a=document.createElement('a');a.href=url;a.style.display='none';a.download='aaa.webm';a.click();
}

  • 采集屏面数据
//getDisplayMedia 捕获桌面 ,getUserMedia  捕获摄像头数据
function start(){//捕获桌面if (!navigator.mediaDevices||!navigator.mediaDevices.getDisplayMedia) {          console.log("getUserMedia is not supported!")return;} else {//捕获桌面var constraints1={video: true,audio: true,}//getDisplayMedia 捕获桌面 ,getUserMedia  捕获摄像头数据navigator.mediaDevices.getDisplayMedia(constraints1).then(gotMediaStream).then(gotDevices).catch(handleError)}
}

采集屏幕数据其实和采集音视频信息一直,只是将getUserMedia替换成getDisplayMedia即可.

注意:要使用google浏览器打开Experimental Web Platform features


全部代码

  • html

<html><head><title>WebRtc  capture video and audio</title><style>.none{-webkit-filter:none;}.blur{-webkit-filter:blur(3px);}.grayscale{-webkit-filter:grayscale(1);}.invert{-webkit-filter:invert(1);}.sepia{-webkit-filter:sepia(1);}</style></head><body><div><label>audio input device:</label><select id="audioSource"></select></div><div><label>audio output device:</label><select id="audioOutput"></select></div><div><label>video input device:</label><select id="videoSource"></select></div><div><label>Filter:</label><select id="filter"><option value="none">None</option><option value="blur">blur</option><option value="grayscale">Grayscale</option><option value="invert">Invert</option><option value="sepia">sepia</option></select></div><div><table><tr><td><video autoplay playsinline id="player"></video></td><td><video  playsinline id="recplayer"></video></td><td><div id="constraints" class="output"></div></td></tr><tr><td><button id="record">Start Record</button></td><td><button id="recplay" disabled>Play</button></td><td><button id="download" disabled>Download</button></td></tr></table></div><!--从视频中获取图片--><div><button id="snapshot">Take snapshot</button></div><div><canvas id="picture"></canvas></div><script src="https://webrtc.github.io/adapter/adapter-latest.js"></script><script src="./js/client.js"></script></body>
</html>
  • js
'use strict'var videoplay=document.querySelector('video#player')var audioSource =document.querySelector("select#audioSource");
var audioOutput =document.querySelector("select#audioOutput");
var videoSource =document.querySelector("select#videoSource");//特效
var filtersSelect =document.querySelector("select#filter");//从视频中获取图片
var snapshot =document.querySelector("button#snapshot");
var picture =document.querySelector("canvas#picture");
picture.width=480;
picture.height=640;//获取屏幕约束
var divConstraints = document.querySelector('div#constraints')//录制音视频
var recvideo = document.querySelector('video#recplayer')
var btnRecord = document.querySelector('button#record')
var btnPlay = document.querySelector('button#recplay')
var btnDownload = document.querySelector('button#download')var buffer;
var mediaRecorder;function gotMediaStream(stream){var videoTrack = stream.getVideoTracks()[0];var videoConstraints =  videoTrack.getSettings();divConstraints.textContent=   JSON.stringify(videoConstraints,null,2);window.stream=stream;videoplay.srcObject=stream;return navigator.mediaDevices.enumerateDevices();
}function handleError(err){console.log("getUserMedia  error:",err);
}function gotDevices(deviceInfos){deviceInfos.forEach(function(deviceinfo){var option= document.createElement('option');option.text=deviceinfo.label;option.value=deviceinfo.deviceId;if(deviceinfo.kind==='audioinput'){audioSource.appendChild(option);}else if(deviceinfo.kind==='audiooutput'){audioOutput.appendChild(option);}else if(deviceinfo.kind==='videoinput'){videoSource.appendChild(option);}})
}//getDisplayMedia 捕获桌面 ,getUserMedia  捕获摄像头数据
function start(){//捕获摄像头数据if (!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia) {//捕获桌面// if (!navigator.mediaDevices||//      !navigator.mediaDevices.getDisplayMedia) {          console.log("getUserMedia is not supported!")return;} else {var deviceId=videoSource.value;//捕获摄像头数据var constraints={video: {width:640,height:480,frameRate:30,//environment:后置摄像头,user:前置摄像头facingMode:"user",deviceId: {exact:deviceId ? deviceId:undefined}},audio: {//降噪noiseSuppression:true,//回音消除echoCancellation:true},}//捕获桌面var constraints1={video: true,audio: true,}//getDisplayMedia 捕获桌面 ,getUserMedia  捕获摄像头数据navigator.mediaDevices.getUserMedia(constraints)// navigator.mediaDevices.getDisplayMedia(constraints1).then(gotMediaStream).then(gotDevices).catch(handleError)}
}start();videoSource.onchange=start;//特效
filtersSelect.onchange = function(){videoplay.className=filtersSelect.value;
}//从视频中获取图片
snapshot.onclick=function(){picture.className=filtersSelect.valuepicture.getContext('2d').drawImage(videoplay,0,0,picture.width,picture.height);}//视频录制
btnRecord.onclick=()=>{if(btnRecord.textContent==='Start Record'){startRecord();btnRecord.textContent='Stop Record'btnPlay.disabled=true;btnDownload.disabled=true;}else{stopRecord();btnRecord.textContent='Start Record'btnPlay.disabled=false;btnDownload.disabled=false;}
}function handleDataAvailable(e){if(e&&e.data&&e.data.size>0){buffer.push(e.data)}
}
function startRecord(){buffer=[];var options={mimeType: 'video/webm;codecs=vp8'}if(!window.MediaRecorder.isTypeSupported(options.mimeType)){console.error('${options.mimeType} is not supported');return;}try {mediaRecorder= new window.MediaRecorder(window.stream,options);} catch (e) {console.error('failed to create  MediaRecorder:',e);return;}mediaRecorder.ondataavailable= handleDataAvailable;mediaRecorder.start(10);
}
function stopRecord(){mediaRecorder.stop();
}btnPlay.onclick=()=>{var blob =new Blob(buffer,{type: 'video/webm'});recvideo.src=window.URL.createObjectURL(blob);recvideo.srcObject=null;recvideo.controls=true;recvideo.play();
}btnDownload.onclick=()=>{var blob =new Blob(buffer,{type:'video/webm'});var url = window.URL.createObjectURL(blob);var a=document.createElement('a');a.href=url;a.style.display='none';a.download='aaa.webm';a.click();
}

这里提供一个我自己的测试地址:https://www.huangxiaoguo.club/mediastream/index.html

webRTC(四):Webrtc音视频数据采集录制采集屏面数据相关推荐

  1. 流媒体开发(四)音视频的录制

    在前面几篇文章中,我们介绍了在iOS中如何实现音视频的播放,在本文中,我们将介绍一下在iOS中如何实现音视频的录制功能. 1. 音频录制 在AVFoundation框架中还要一个AVAudioReco ...

  2. webrtc简单案例——音视频采集和播放

    webrtc简单案例--音视频采集和播放 目录 打开摄像头并将画面显示到页面 打开麦克风并在页面播放捕获的声音 同时打开摄像头和麦克风,并在页面显示画面和播放捕获的声音 1. 打开摄像头并将画面显示到 ...

  3. 基于WebRTC实现1v1音视频聊天室

    一. 前言 WebRTC(Web Real-Time Communication)旨在将实时通信功能引入到浏览器,用户无需安装其他任何软件或插件即可在浏览器间进行实时通信功能.本文介绍基于 WebRT ...

  4. WebRTC 中收集音视频编解码能力

    在 WebRTC 中,交互的两端在建立连接过程中,需要通过 ICE 协议,交换各自的音视频编解码能力,如编解码器和编解码器的一些参数配置,并协商出一组配置和参数,用于后续的音视频传输过程. 对于音频, ...

  5. 基于webrtc多人音视频的研究(一)

    所周知,WebRTC非常适合点对点(即一对一)的音视频会话.然而,当我们的客户要求超越一对一,即一对多.多对一设置多对多的解决方案或者服务,那么问题就来了:"我们应该采用什么样的架构?&qu ...

  6. 【转】WebRTC多人音视频解决方案

    文章目录 1. 引言 2. 解决方案 2.1 Mesh解决方案 2.2 Mixer解决方案 2.3 Router解决方案 2.4 三个解决方案的流量对比 3. 应该使用哪种架构? 4. 参考资料 1. ...

  7. iOS WebRTC多人音视频建立的流程

    前言 本文主要以"代码是最好的注释"为基点,介绍在处理iOS端多人音视频的建立流程. 在看本篇前建议先了解一下多人音视频通讯现在的常用架构,参考<WebRTC多人音视频聊天架 ...

  8. JS基于页面实现音视频的录制(一)

    前言 音频与视频信息的捕捉一直是Web开发中的一个难点.许多年来,我们一直依赖浏览器插件来实现这个需求,随着HTML 5推出,这种情况有所改变.因为,HTML5提供了许多可以访问硬件设备的API,例如 ...

  9. 将音视频中的花屏、绿屏、黑屏问题一网打尽

    今天继续给大家分享一下知识星球里面的干货. 创建知识星球快两个月了,目前已经积累了不少干货,主要得益于星球里大佬们的分享以及小伙伴的提问. 星球里面邀请的大佬都是在头条.快手等知名 IT 企业从事过音 ...

最新文章

  1. 安装很久_快看啦!吊轨推拉门安装图解在这里。
  2. JZOJ 5244. 【NOIP2017模拟8.8A组】Daydreamin ' (daydream)
  3. android第三方应用,Android 第三方应用接入微信平台研究情况分享(一)
  4. 【Java 强化】单元测试(JUnit3、JUnit4)、XML(语法、约束、文档结构)、DOM、DOM4J
  5. Maya vray XYZ皮肤贴图材质节点连接
  6. Unity WebGL基于js通信实现网页录音
  7. 企业做营销型网站的目的
  8. 自然语言处理技术及处理框架学习
  9. docker部署es和kibana遇到的坑
  10. CF1324F Maximum White Subtree
  11. 杨辉三角 (java语言)
  12. 用python简易英汉互译界面_python之做一个简易的翻译器(一)
  13. 【论文泛读】Multi-modal Sarcasm Detection and Humor Classification in Code-mixed Conversations
  14. 你还在纠结器件丝印放错的烦恼么?
  15. 人脸验证与人脸识别(Face verification and Face identification / recognition)
  16. 静态代理之AspectJ编译织入
  17. 公司位置怎么上地图,区域网格分布图怎么做
  18. 别怕未来会把过去写旧【1】
  19. android composite adb interface,【玩机组】Android Composite ADB Interface在XP下无法安装解决方法...
  20. ps和netstat

热门文章

  1. 你真的了解网站备案吗?网站备案资质类型有哪些?
  2. NetData搭建 -- Linux性能实时监测工具
  3. 使用 Java 实现指定概率的抽奖
  4. sql优化之explain关键字分析
  5. Conda及常用生信软件安装
  6. 为使在本计算机系统中开发的硬,计算机应用基础统考题库新网考计算机应用基础真题...
  7. 我心目中理想的“元宇宙”
  8. 如何使用密码限制对PlayStation 4的访问
  9. Python数据可视化:数据关系图表可视化(基础篇—3)
  10. 年薪可达50万!上海交大SEIEE·云智AI创新应用研究中心招聘研发工程师