下面的代码允许用户启动录制,然后将其回放给用户:
<body>
<div>
<h2>Audio record and playback</h2>
<p>
<button id=startRecord>start</button>
<button id=stopRecord disabled>stop</button>
</p>
<p>
<audio id=recordedAudio></audio>
<a id=audioDownload></a>
</p>
</div>
</body>
<script>
(function() {
// your page initialization code here
// the DOM will be available here
navigator.mediaDevices.getUserMedia({audio:true})
.then(stream => {
rec = new MediaRecorder(stream);
rec.ondataavailable = e => {
audioChunks.push(e.data);
if (rec.state == "inactive"){
let blob = new Blob(audioChunks,{type:'audio/x-mpeg-3'});
recordedAudio.src = URL.createObjectURL(blob);
recordedAudio.controls=true;
recordedAudio.autoplay=true;
audioDownload.href = recordedAudio.src;
audioDownload.download = 'mp3';
audioDownload.innerHTML = 'download';
}
}
})
.catch(e=>console.log(e));
startRecord.onclick = e => {
startRecord.disabled = true;
stopRecord.disabled=false;
audioChunks = [];
rec.start();
}
stopRecord.onclick = e => {
startRecord.disabled = false;
stopRecord.disabled=true;
rec.stop();
}
})();
</script>
我正在尝试修改代码,以便每5秒保存一次记录。我应该如何以编程方式启动和停止录制功能?
我已经尝试过:
rec.start();
var i = 0, howManyTimes = 10;
function f() {
i++;
if( i < howManyTimes ){
setTimeout( f, 5000 );
rec.stop();
rec.start();
}
}
f();
但是返回错误:
ReferenceError: rec is not defined