<!--这是一位大佬的代码,我只是转发-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<audio controls id="audioPlay"></audio>
<button id="btnRecord">开始录制</button>
<button disabled id="btnPlay">开始播放</button>
<button disabled id="btnDownload">开始下载</button>
<script>
var audioPlay = document.querySelector('audio#audioPlay');
var btnRecord = document.querySelector('button#btnRecord');
var btnPlay = document.querySelector('button#btnPlay');
var btnDownload = document.querySelector('button#btnDownload');
navigator.mediaDevices.getUserMedia({audio:true})
.then(gotMediaStream);
function gotMediaStream(stream){
window.stream = stream;
}
btnRecord.onclick = () => {
if(btnRecord.textContent === '开始录制'){
startRecord();
btnRecord.textContent = '停止录制';
btnPlay.disabled = true;
btnDownload.disabled = true;
}else{
stopRecord();
btnRecord.textContent = '开始录制';
btnPlay.disabled = false;
btnDownload.disabled = false;
}
}
function startRecord(){
buffer = [];
mediaRecorder = new MediaRecorder(window.stream,{audio:true});
mediaRecorder.ondataavailable = handleDataAvailable;
mediaRecorder.start(10) //每隔10毫秒存储一块数据
}
var buffer;
function handleDataAvailable(e) {
buffer.push(e.data);
}
function stopRecord() {
mediaRecorder.stop();
}
btnPlay.onclick = () => {
//使用Blob对象
var blob = new Blob(buffer, { type: 'audio/ogg' });
//获取资源
audioPlay.src = window.URL.createObjectURL(blob);
//控制标签
audioPlay.controls = true;
//开始播放
audioPlay.play();
}
btnDownload.onclick = () => {
var blob = new Blob(buffer, { type: 'audio/ogg' });
url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = 'juejin.ogg';
a.click();
}
</script>
</body>
</html>