赞
踩
mediaDevices.getUserMedi() 向用户申请录音权限,返回一个promise对象
MediaRecorder() 提供录制的接口
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <audio id="audio" src="" controls></audio> <button id="record">开始录音</button> <script> // 获取录音按钮 const recordBtn = document.querySelector('#record') // 获取audio const audio = document.querySelector('#audio') const audioStream = { status: false, // 录音状态 streams: [], // 用于存储录音stream blob: null, // stream转换成的blob } // MediaRecorder实例 let mediaRecorder = null // 给录音按钮添加点击事件 recordBtn.addEventListener('click', async (e) => { // 判断录音状态 if (audioStream.status) { controlMediaRecorder() } else { // 判断mediaRecorder是否存在 mediaRecorder ? controlMediaRecorder() : getpermission() } }) // 获取权限 function getpermission() { // audio 音频 | video 视频 const constraints = { audio: true, video: false } navigator.mediaDevices.getUserMedia(constraints).then((MediaStream) => { // 获取成功 得到媒体流 MediaStream 并实例一个MediaRecorder对象 mediaRecorder = new MediaRecorder(MediaStream); mediaRecorder.addEventListener('dataavailable', onDataavailable) mediaRecorder.addEventListener('stop', onStop) controlMediaRecorder() }).catch((error) => { // 获取失败 console.error(error); }) } // 控制MediaRecorder function controlMediaRecorder() { // 判断录音状态 // inactive 休息 | recording 录音中 | paused 暂停 if (mediaRecorder.state == 'inactive') { // 开始录制将之前的录音清空 audioStream.streams = [] // 释放内存 if (audioStream.blob) { URL.revokeObjectURL(audioStream.blob) audioStream.blob = null } mediaRecorder.start(1000) recordBtn.innerText = '结束录制' audioStream.status = true console.log("开始录制---"); } else { mediaRecorder.stop() recordBtn.innerText = '开始录制' audioStream.status = false console.log("结束录制---"); } } // 监听stop事件 function onStop() { // 将audioStream.streams转换为地址 audioStream.blob = new Blob(audioStream.streams, { type: audioStream.streams[0].type }) audio.src = URL.createObjectURL(audioStream.blob) } /** * 监听录音dataavailable事件 * 触发条件 * 1. 媒体流结束时 * 2. 调用stop() * 3. 调用requestData() * 4. 调用start(timeslice) 每隔 timeslice 毫秒触发一次 dataavailable事件 */ function onDataavailable(event) { // event.data blob对象 audioStream.streams.push(event.data) } </script> </body> </html>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。