| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <html>
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>getUserMedia test</title>
- </head>
- <body>
- <button onclick="shotCut()">切换摄像头</button>
- <video id="video" autoplay="true" playsinline></video>
- <script>
- var video = document.querySelector("#video");
- var front = false;
- var nativeStream
- var videoInputDevices = []
- JSON.stringify()
- if((navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
-
- navigator.mediaDevices.getUserMedia({
- // video: { facingMode: "user" },
- video: { facingMode: "environment" },
- audio: false
- })
- .then(function(stream) {
- mediumInfo()
- video.srcObject = stream;
- nativeStream = stream
- video.play();
- })
- .catch(function(err) {
- console.log("你拒绝使用相机:" + err);
- });
- } else {
- console.log("您的浏览器不支持影像功能");
- }
- //获取摄像头,音频设备信息
- function mediumInfo() {
- navigator.mediaDevices.enumerateDevices()
- .then(gotDevices).catch(handleError);
-
- function gotDevices(deviceInfos) {
- deviceInfos.forEach(function(n) {
- if(n.kind === 'videoinput') {
- videoInputDevices.push(n);
- }
- })
- alert(JSON.stringify(videoInputDevices))
- }
-
- function handleError(error) {
- //alert(JSON.stringify(error));
- }
- }
- //切换摄像头
- function shotCut() {
- front = !front
- //关闭本地媒体流
- if(nativeStream) {
- nativeStream.getVideoTracks()[0].stop();
- }
- navigator.mediaDevices.getUserMedia({
- audio: false, //这里是为了摄像头切换时,回显本地媒体,禁止本地声音
- video: { facingMode: (front? "user" : "environment") }
- }).then((stream) => {
- //本地摄像头切换
- nativeStream = stream
- video.srcObject = nativeStream;
- //微信端浏览器适配,需要先stop,然后执行这个函数
- video.onloadedmetadata = function() { //媒体流直接关闭掉后这里会重新执行
- if(nativeStream.active) { //在这里需要做判断,判断媒体流处于活动状态
- video.play();
- }
- }
- }).catch((res) => {
- alert('getUserMedia() error1: ' + res.name);
- })
- // try {
- //
- //
- // } catch(e) {
- // alert(JSON.stringify(e));
- // }
- }
- </script>
- </body>
- </html>
|