html-basic
2024年02月06日
一、认识
1.1 视频水平翻转
只需要将 video
的样式设置为 transform: scaleX(-1)
即可。
video.style.transform = "scaleX(-1)";
二、实现
<div class="operation">
<button id="start-record">录制</button>
<button id="stop-record">停止</button>
</div>
<div class="video-container">
<video id="video" autoplay></video>
</div>
<script>
let mediaRecorder = null;
const recordedBlobs = [];
const video = document.getElementById('video');
const startRecordEl = document.getElementById('start-record');
const stopRecordEl = document.getElementById('stop-record');
function startRecord() {
const timeSlice = 5000;
mediaRecorder.start(timeSlice);
}
async function stopRecord() {
const stream = video.srcObject;
const tracks = stream.getTracks();
tracks.forEach(track => {
track.stop();
});
video.srcObject = null;
mediaRecorder.stop();
}
async function prepareRecord() {
const stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
video.srcObject = stream;
video.play();
mediaRecorder = new MediaRecorder(stream, {
mimeType: 'video/webm'
});
mediaRecorder.ondataavailable = event => {
if (event.data && event.data.size > 0) {
recordedBlobs.push(event.data);
}
};
}
async function checkPermissions(name) {
try {
return await navigator.permissions.query({ name: name });
} catch (error) {
return {
state: "denied"
};
}
}
async function run() {
const camera = await checkPermissions('camera');
const microphone = await checkPermissions('microphone');
if (camera.state === 'granted' && microphone.state === 'granted') {
prepareRecord();
startRecordEl.addEventListener('click', startRecord);
stopRecordEl.addEventListener('click', stopRecord);
} else {
alert('请允许使用摄像头和麦克风');
}
}
run();
</script>