html5 获取摄像头和麦克风的案例

xiaoxiao2021-02-27  123

使用的接口api

通过navigator.mediaDevices.getUserMedia()方法进行获取 该MediaDevices.getUserMedia()方法提示用户允许使用产生MediaStream包含所请求类型的媒体的轨道的媒体输入。该流可以包括例如视频轨道(由硬件或虚拟视频源(例如相机,视频记录设备,屏幕共享服务等)产生),音轨(类似地,由物理或虚拟音频源,如麦克风,A / D转换器等),以及可能的其他轨道类型。 注意:使用此方法需要允许浏览器调用摄像头和麦克风才可以

代码案例

当前代码直接在pc端或者笔记本上可直接查看案例,如果缺少相关硬件,直接回给报错误。

<!doctype html> <html lang="en"> <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> <video src="" id="video"></video> </body> <script> // Prefer camera resolution nearest to 1280x720. var constraints = { audio: true, video: { width: 1280, height: 720 } }; navigator.mediaDevices.getUserMedia(constraints) .then(function(mediaStream) { var video = document.querySelector('video'); video.srcObject = mediaStream; video.onloadedmetadata = function(e) { video.play(); }; }) .catch(function(err) { console.log(err.name + ": " + err.message); }); // always check for errors at the end. </script> </html>

兼容性

火狐 谷歌chorme 还有欧朋浏览器都支持 ie浏览器和苹果的safari都不支持

注意事项

在移动端http协议不被支持,需要在https更安全的协议上面使用。

转载请注明原文地址: https://www.6miu.com/read-16016.html

最新回复(0)