本文主要是介绍js的MediaRecorder录音录视频方法笔记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/**
* 录音举例说明
* https://www.cnblogs.com/zaijin-yang/p/17306578.html
* 通过 web 录制视频(摄像头)并上传
* https://cloud.tencent.com/developer/article/1818977?areaId=106001
* 视频录制基础知识-MediaRecorder
* https://www.jianshu.com/p/ad7dfd50880e
*/
import React, { useState, useEffect } from 'react'var mediaRecorder
var stream
var chunks = []
export default function App() {return (<MyRecord />);
}function MyRecord() {var [fileSize, setFileSize] = useState(0)var [url, setUrl] = useState(null)/*** 录音举例说明* https://www.cnblogs.com/zaijin-yang/p/17306578.html* 通过 web 录制视频(摄像头)并上传* https://cloud.tencent.com/developer/article/1818977?areaId=106001* 视频录制基础知识-MediaRecorder* https://www.jianshu.com/p/ad7dfd50880e*/async function initRecord() {//stream = await navigator.mediaDevices.getUserMedia({ audio: true })try {stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })// const videoElement = document.querySelector('video');// videoElement.srcObject = stream;//通过调用getUserMedia方法获取摄像头的实时视频流,并将其赋值给srcObject属性,从而在网页上显示实时视频。//src适用于加载已有的静态视频文件。//srcObject适用于处理实时视频流,比如从摄像头捕获到的视频。mediaRecorder = new MediaRecorder(stream);mediaRecorder.ondataavailable = event => {if (event.data.size > 0) {console.log('======ondataavailable事件触发,chunks.length:', chunks.length);setFileSize(event.data.size)chunks.push(event.data); // 将数据块追加到 chunks 数组中 }};mediaRecorder.onstop = () => {console.log('======按下了停止录音键', mediaRecorder.mimeType);const blob = new Blob(chunks, { type: mediaRecorder.mimeType }); // 将数据块转换为 Blob // 此时你可以使用 blob 对象,比如上传到服务器或保存到本地文件console.log('Blob created:', blob.size);const url = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象const audio = document.getElementById("aaaa"); //创建标签audio.src = url;//销毁视频,释放资源URL.revokeObjectURL(url)}} catch (e) {console.log('用户禁止了摄像头权限')}}function startRecord() {chunks = []mediaRecorder.start();}function stopRecord() {/*** mediaRecorder.state返回当前状态 (闲置中,录制中或者暂停 ) (inactive, recording, or paused.)*/if (mediaRecorder.state === "recording") {mediaRecorder.stop();}}function destroyRecord() {// 终止流(这可以让浏览器上正在录音的标志消失掉)stream.getTracks().forEach(track => track.stop());stream = null;}function pauseRecord() {mediaRecorder.pause();}function resumeRecord() {mediaRecorder.resume();}var ss = { fontSize: '20px', margin: '10px' }return (<div><video id="aaaa" controls playsInline style={{ width: '300px', height: '200px' }}></video><h3>文件大小:{fileSize}</h3><button style={ss} onClick={initRecord}>初始化录音</button><button style={ss} onClick={startRecord}>开始录音</button><button style={ss} onClick={stopRecord}>停止录音</button><button style={ss} onClick={destroyRecord}>销毁录音</button><button style={ss} onClick={pauseRecord}>暂停录音</button><button style={ss} onClick={resumeRecord}>恢复录制</button></div >);
}
这篇关于js的MediaRecorder录音录视频方法笔记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!