
!DOCTYPE htmlhtml langzh-CNheadmeta charsetUTF-8meta nameviewport contentwidthdevice-width, initial-scale1.0, maximum-scale1.0, user-scalablenotitleH5 活体录像验证 (最终修正版)/title!-- 引入 vConsole --script srchttps://unpkg.com/vconsolelatest/dist/vconsole.min.js/scriptstyle* { box-sizing: border-box; margin: 0; padding: 0; }body {font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, sans-serif;display: flex;flex-direction: column;align-items: center;justify-content: center;min-height: 100vh;background-color: #f5f7fa;color: #333;padding: 20px;}/* 视频容器样式 */#video-container {width: 100%;max-width: 480px;aspect-ratio: 16 / 9;background-color: #000;border-radius: 12px;overflow: hidden;position: relative;box-shadow: 0 4px 12px rgba(0,0,0,0.1);margin-bottom: 24px;}video {width: 100%;height: 100%;object-fit: cover;transform: scaleX(-1); /* 镜像显示 */}/* 录制中状态指示器 - 右上角淡色小按钮 */#recording-indicator {position: absolute;top: 12px;right: 12px;background-color: rgba(255, 59, 48, 0.15); /* 淡红色背景 */color: #ff3b30;font-size: 12px;font-weight: 600;padding: 4px 10px;border-radius: 12px;display: none; /* 默认隐藏 */align-items: center;gap: 6px;backdrop-filter: blur(4px);z-index: 10;animation: breathe 1.5s infinite ease-in-out;}#recording-indicator::before {content: ;display: block;width: 6px;height: 6px;background-color: #ff3b30;border-radius: 50%;}keyframes breathe {0%, 100% { opacity: 0.6; transform: scale(0.98); }50% { opacity: 1; transform: scale(1.02); }}/* 倒计时提示 */#countdown {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);font-size: 48px;font-weight: bold;color: white;text-shadow: 0 2px 4px rgba(0,0,0,0.5);display: none;z-index: 5;}/* 按钮组样式 */.btn-group {display: flex;gap: 16px;width: 100%;max-width: 480px;margin-bottom: 16px;}button {flex: 1;padding: 14px 0;border: none;border-radius: 8px;font-size: 16px;font-weight: 600;cursor: pointer;transition: all 0.2s;}button:active { transform: scale(0.98); }#startBtn {background-color: #007aff;color: white;}#saveBtn {background-color: #34c759;color: white;display: none;}#closeBtn {background-color: #ff9500;color: white;display: none;}/* 状态文本 */#statusText {font-size: 14px;color: #666;text-align: center;min-height: 20px;}/* 结果预览区 */#resultContainer {width: 100%;max-width: 480px;margin-top: 20px;display: none;}#resultVideo {width: 100%;border-radius: 8px;background: #000;}.file-info {margin-top: 8px;font-size: 12px;color: #888;text-align: center;}/style/headbodydiv idvideo-containervideo idpreview autoplay playsinline muted/video!-- 录制中指示器 --div idrecording-indicator录制中/div!-- 倒计时 --div idcountdown3/div/divdiv classbtn-groupbutton idstartBtn开始验证/buttonbutton idsaveBtn保存视频/buttonbutton idcloseBtn关闭摄像头/button/divp idstatusText准备就绪/p!-- 结果预览 --div idresultContainervideo idresultVideo controls/videodiv classfile-info idfileInfo/div/divscript// 初始化 vConsoleconst vConsole new window.VConsole();console.log([System] vConsole 已启动);// DOM 元素const preview document.getElementById(preview);const startBtn document.getElementById(startBtn);const saveBtn document.getElementById(saveBtn);const closeBtn document.getElementById(closeBtn);const statusText document.getElementById(statusText);const recordingIndicator document.getElementById(recording-indicator);const countdownEl document.getElementById(countdown);const resultContainer document.getElementById(resultContainer);const resultVideo document.getElementById(resultVideo);const fileInfo document.getElementById(fileInfo);// 全局变量let mediaStream null;let recorder null;let recordedChunks [];let currentBlob null;let isRecording false;// 配置参数const CONFIG {duration: 6000, // 6秒自动结束maxSize: 10 * 1024 * 1024, // 10MB 限制// 源头控制限制分辨率和帧率constraints: {audio: false,video: {width: { ideal: 640, max: 1280 },height: { ideal: 480, max: 720 },frameRate: { ideal: 20, max: 24 }}}};/*** 核心类RecorderManager* 包含录制、自动停止、二次压缩逻辑*/class RecorderManager {constructor(stream) {this.stream stream;this.chunks [];this.recorder null;// 尝试选择兼容性最好的编码格式const options { mimeType: video/webm;codecsvp9 };if (!MediaRecorder.isTypeSupported(options.mimeType)) {options.mimeType video/webm;codecsvp8;if (!MediaRecorder.isTypeSupported(options.mimeType)) {options.mimeType video/webm;}}// 过程建议设置码率虽然浏览器不一定完全遵守options.videoBitsPerSecond 1500000; // 1.5Mbpsthis.recorder new MediaRecorder(this.stream, options);console.log([Recorder] 初始化完成MIME: ${options.mimeType});this.recorder.ondataavailable (e) {if (e.data e.data.size 0) {this.chunks.push(e.data);// 实时打印当前累计大小方便调试const currentSize this.chunks.reduce((acc, cur) acc cur.size, 0);console.log([Recorder] 接收数据块: ${(currentSize / 1024).toFixed(2)} KB);}};this.recorder.onstop () {console.log([Recorder] 录制已停止);const blob new Blob(this.chunks, { type: this.recorder.mimeType });this.handleFinish(blob);};}start() {this.chunks [];this.recorder.start(100); // 每100ms触发一次 dataavailableisRecording true;// 显示 UIrecordingIndicator.style.display flex;statusText.textContent 正在录制...;console.log([Recorder] 开始录制);// 6秒倒计时 UIlet count 3;countdownEl.style.display block;countdownEl.textContent count;const timer setInterval(() {count--;if (count 0) {countdownEl.textContent count;} else {clearInterval(timer);countdownEl.style.display none;}}, 1000);// 6秒后自动停止setTimeout(() {if (this.recorder this.recorder.state recording) {console.log([Recorder] 触发6秒自动停止);this.stop();}}, CONFIG.duration);}stop() {if (this.recorder this.recorder.state ! inactive) {this.recorder.stop();}}async handleFinish(blob) {isRecording false;recordingIndicator.style.display none; // 隐藏录制中标识console.log([Recorder] 原始文件大小: ${(blob.size / 1024 / 1024).toFixed(2)} MB);// 结果兜底如果超过 10MB进行二次压缩if (blob.size CONFIG.maxSize) {console.warn([Recorder] 文件过大启动二次压缩...);statusText.textContent 文件过大正在压缩...;try {blob await this.compressBlob(blob);console.log([Recorder] 压缩后大小: ${(blob.size / 1024 / 1024).toFixed(2)} MB);} catch (err) {console.error([Recorder] 压缩失败:, err);statusText.textContent 压缩失败请重试;return;}}currentBlob blob;this.showResult(blob);}/*** 二次压缩利用 MediaRecorder 重新编码* 不依赖第三方库通过降低码率实现压缩*/compressBlob(originalBlob) {return new Promise((resolve, reject) {const url URL.createObjectURL(originalBlob);const tempVideo document.createElement(video);tempVideo.src url;tempVideo.muted true;tempVideo.playsInline true;// 创建一个新的低码率录制器const compressOptions {mimeType: video/webm,videoBitsPerSecond: 500000 // 500kbps 极低码率};let compressChunks [];let compressRecorder;tempVideo.onloadedmetadata () {try {// 捕获视频流进行重录const stream tempVideo.captureStream ? tempVideo.captureStream() : tempVideo.mozCaptureStream();compressRecorder new MediaRecorder(stream, compressOptions);compressRecorder.ondataavailable (e) {if (e.data.size 0) compressChunks.push(e.data);};compressRecorder.onstop () {URL.revokeObjectURL(url);const compressedBlob new Blob(compressChunks, { type: video/webm });resolve(compressedBlob);};compressRecorder.start();tempVideo.play();// 播放完毕即压缩完成tempVideo.onended () {if (compressRecorder.state ! inactive) {compressRecorder.stop();}};} catch (e) {URL.revokeObjectURL(url);reject(e);}};tempVideo.onerror () reject(new Error(视频加载失败));});}showResult(blob) {const url URL.createObjectURL(blob);resultVideo.src url;resultContainer.style.display block;fileInfo.textContent 大小: ${(blob.size / 1024).toFixed(2)} KB | 类型: ${blob.type};saveBtn.style.display block;closeBtn.style.display block;startBtn.textContent 重新验证;statusText.textContent ✅ 录制完成;}destroy() {if (this.stream) {this.stream.getTracks().forEach(track track.stop());}this.stream null;this.recorder null;}}let manager null;// 1. 开始验证startBtn.addEventListener(click, async () {try {statusText.textContent 正在开启摄像头...;console.log([UI] 点击开始验证);// 获取媒体流mediaStream await navigator.mediaDevices.getUserMedia(CONFIG.constraints);preview.srcObject mediaStream;// 实例化管理器并开始manager new RecorderManager(mediaStream);manager.start();startBtn.style.display none;resultContainer.style.display none;} catch (err) {console.error([Error] 获取摄像头失败:, err);statusText.textContent ❌ 无法访问摄像头: err.message;}});// 2. 保存视频saveBtn.addEventListener(click, () {if (!currentBlob) return;const url URL.createObjectURL(currentBlob);const a document.createElement(a);a.href url;a.download liveness_${Date.now()}.webm;document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);console.log([UI] 视频已下载);});// 3. 关闭摄像头closeBtn.addEventListener(click, () {if (manager) {manager.destroy();manager null;}preview.srcObject null;currentBlob null;saveBtn.style.display none;closeBtn.style.display none;startBtn.style.display block;startBtn.textContent 开始验证;statusText.textContent 摄像头已安全关闭;recordingIndicator.style.display none; // 确保关闭时隐藏console.log([UI] 摄像头已关闭);});/script/body/html