1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| <!DOCTYPE html> <html> <head> <title>H5获取摄像头和麦克风</title> <meta name="renderer" content="webkit"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,user-scalable=no"> <link rel="prefetch prerender" href=""> <script type="text/javascript" src="//public.yitong.com/libs/html5shiv/3.7.3/html5shiv.min.js"></script> <script type="text/javascript" src="//public.yitong.com/libs/respond.js/1.4.2/respond.min.js"></script> <script type="text/javascript" src="//public.yitong.com/libs/jquery/1.11.1/jquery.min.js"></script> <style type="text/css"> #myVolumeText { display: inline-block; width:1.5em; } #myVolume { display: inline-block; height:16px; width:0px; background-color: greenyellow; position: relative; top:3px; } </style> </head> <body> <video id="webcam"></video> <div>当前音量:<span id="myVolumeText"></span><span id="myVolume"></span></div> </body> <script> window.AudioContext = window.AudioContext window.webkitAudioContext; var myAudioContext = new AudioContext(); navigator.getUserMedia = navigator.getUserMedia navigator.webkitGetUserMedia navigator.mozGetUserMedia navigator.msGetUserMedia; navigator.getUserMedia({ video:true, audio:true },function(stream){ console.log("【log】获取权限成功!") onSuccess(stream) },function(error){ console.log("【log】获取权限失败!") console.log("【log】错误信息:"+error.name) })
function onSuccess(stream) { videoFun(stream) audioFun(stream) }
function videoFun(stream){ var video = document.getElementById("webcam"); if(window.URL){ video.src = window.URL.createObjectURL(stream) }else{ video.src = stream; } video.autoplay = true; }
var liveSource,levelChecker; function audioFun(stream){ var liveSource = myAudioContext.createMediaStreamSource(stream); var levelChecker = myAudioContext.createScriptProcessor(4096,1,1); liveSource.connect(levelChecker); levelChecker.connect(myAudioContext.destination); levelChecker.onaudioprocess = function(e) { var buffer = e.inputBuffer.getChannelData(0); var maxVal = 0; for (var i = 0; i < buffer.length; i++) { if (maxVal < buffer[i]) { maxVal = buffer[i]; } } var num = Math.round(maxVal*100) num = (num>100?100:num) document.getElementById("myVolume").style.width = 5*num + "px"; document.getElementById("myVolumeText").innerHTML = num; console.log("当前音量值:" + num) }; } function endAudioFun(){ liveSource.disconnect(levelChecker); levelChecker.disconnect(myAudioContext.destination); } </script> </html>
|