javascript 最简单的录音代码
作者:互联网
最简单的录音
效果图
更复杂的内容可以查看手册请
多媒体开发手册
<html>
<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 name="apple-mobile-web-capable" content="yes">
<title>最简单录音代码</title>
</head>
<body>
<div id="container">
<div id="player">
<h1>最简单录音代码</h1>
<label id="view" ></label>
</br>
<button id="btn-start-recording">开始录音</button>
<button id="btn-stop-recording">停止录音</button>
<hr>
<audio id='audio' controls autoplay></audio>
</div>
</div>
</body>
</html>
<script>
var startButton = document.getElementById('btn-start-recording');
var stopButton = document.getElementById('btn-stop-recording');
var audio = document.getElementById('audio');
var blob;
var mediaRecorder;
//开始按钮
startButton.onclick = function() {
var txt=document.getElementById("view");
txt.innerHTML="正在录音........,请唱歌..........";
navigator.mediaDevices.getUserMedia({
audio: true
})
.then(onMicrophoneCaptured)
.catch(onMicrophoneCaptureError);
};
//停止按钮
stopButton.onclick = function() {
mediaRecorder.stop();
mediaRecorder.onstop = function(e) {
audio.controls = true;
var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;
}
}
//流媒体录音 function的名字onMicrophoneCaptured 必须和上面代码里的 .then(onMicrophoneCaptured)里的一样
function onMicrophoneCaptured(stream) {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
mediaRecorder.ondataavailable = function(e) {
blob = new Blob([e.data], {
type: 'audio/mp3'
});
}
}
//回调函数 function的名字onMicrophoneCaptureError 必须和上面代码里的 .catch(onMicrophoneCaptureError);里的一样
function onMicrophoneCaptureError() {
alert('浏览器不支持或是用户不允许,请关闭浏览器再来一次')
}
</script>
版本兼容
标签:function,mediaRecorder,代码,javascript,录音,var,audio,document 来源: https://blog.csdn.net/weixin_41315600/article/details/115803332