js 本地视频录制

发布时间 2023-06-06 17:29:11作者: 波仔、
function findNthIndex(str, searchChar, n) {
let index = -1;
for (let i = 0; i < n; i++) {
index = str.indexOf(searchChar, index + 1);
if (index === -1) {
return -1;
}
}
return index;
}
let mediaRecorder = null;
let recordedChunks = [];
const startRecording = () => {
const options = { mimeType: 'video/webm; codecs=vp9' };
mediaRecorder = new MediaRecorder(window.stream, options);
mediaRecorder.ondataavailable = function(e) {
if (e.data.size > 0) {
recordedChunks.push(e.data);
}
};

mediaRecorder.onstop = function(e) {
const blob = new Blob(recordedChunks, { type: 'video/webm' });
recordedChunks = [];
const str = window.URL.createObjectURL(blob)
var a = document.createElement("a"); // 创建a标签
a.setAttribute("href", str); // href链接
a.setAttribute("download", ""); // download属性
a.style.display = "none";
a.click(); // 自执行点击事件
a.remove();
//需要注意的是 生成的是webm格式的文件,仅在谷歌上播放,可以用格式工厂转换成mp4格式的;
// const index =findNthIndex(str,"/",3);
// let newurl = str.slice(index, str.length-1)+".mp4";
// console.log(newurl)
};

mediaRecorder.start();
};

const stopRecording = () => {
console.log("stopRecording")
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
}
};
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then(function(stream) {
window.stream = stream;

// 使用视频流初始化一个 video 元素
const video = document.createElement('video');
video.srcObject = stream;
video.onloadedmetadata = (event) => video.play();

// 将 video 元素放到页面上
document.body.appendChild(video);
})
.catch(function(err) {
console.log('Error:', err);
});

var start = document.querySelector(".start");
var stop = document.querySelector(".stop");
start.onclick = function () {
//开始录制
startRecording()
}
stop.onclick = function () {
//结束录制
stopRecording()
}