You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript录屏函数仅快速双击按钮才生效问题求助

问题解决:录制的视频无法加载,仅双击有效

问题根源

你的代码存在关键时序错误:在调用mediaRecorder.stop()之后才绑定ondataavailable事件。当stop()执行时,浏览器会立即触发ondataavailable事件传递录制数据,但此时事件处理函数还未绑定,导致recordedChunks始终是空数组,生成的Blob没有有效视频数据,自然无法加载。

双击能生效是因为第一次点击的setTimeout还没执行stop(),第二次点击时重新绑定了事件,之后第一次的stop()触发时能捕获到数据,属于巧合的时序漏洞。

修复后的代码

function startRecording() {
  recordedChunks = [];
  const mediaRecorder = new MediaRecorder(mediaStream);
  window.mediaRecorder = mediaRecorder;

  // 先绑定数据接收事件,再启动录制
  mediaRecorder.ondataavailable = (e) => {
    recordedChunks.push(e.data);
  };

  // 在录制停止事件中处理视频生成与播放,确保数据完整
  mediaRecorder.onstop = () => {
    const recordedBlob = new Blob(recordedChunks, { type: "video/mp4" });
    const recordedUrl = URL.createObjectURL(recordedBlob);
    window.recordedUrl = recordedUrl;
    recordingSection.style.display = "none";
    reviewSection.style.display = "flex";
    reviewVideoPlayer.src = recordedUrl;
    reviewVideoPlayer.play();
  };

  mediaRecorder.start();

  setTimeout(() => {
    mediaRecorder.stop();
  }, 2000);
}

function approveRecording() {
  reviewSection.style.display = "flex";
  recordingSection.style.display = "none";
  reviewVideoPlayer.pause();
  reviewVideoPlayer.currentTime = 0;
  reviewVideoPlayer.play();
}

function recordAgain() {
  reviewSection.style.display = "none";
  recordingSection.style.display = "flex";
  reviewVideoPlayer.pause();
  reviewVideoPlayer.currentTime = 0;
  startRecording();
}

startRecordingButton.addEventListener("click", startRecording);
approveButton.addEventListener("click", approveRecording);
recordAgainButton.addEventListener("click", recordAgain);

关键修改说明

  1. 调整事件绑定顺序:将ondataavailable事件绑定移到mediaRecorder.start()之前,确保录制过程中(包括stop()触发时)的所有数据都能被捕获。
  2. 改用onstop事件处理后续逻辑:stop()触发后,ondataavailable会先传递最后一段数据,再触发onstop事件。在onstop里生成Blob和播放视频,能保证recordedChunks已收集到完整的录制数据。

内容的提问来源于stack exchange,提问作者FayezAbulenein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:55:02