我正在尝试将单个块发送到服务器,而不是一次发送整个块。这样,我的 Rails 服务器上就有了 Ffmpeg,可以将这些块转换为 HLS 并将它们上传到 S3 以立即流式传输视频。但是,我遇到了一个问题,媒体记录器仅提供第一段的可播放块,之后它们不可播放,需要连接起来才能播放。
为了避免这种情况,我采取了一种不同的方法,每 3 秒启动一个新的媒体记录器,以便每次都能获得一个可播放的块。然而,这种方法有其问题,由于当我停止并启动新的媒体录制器时出现延迟,视频会出现一些故障。有没有办法轻松实现这一目标?这是我现在的状态。请帮忙!
const startVideoRecording = async (
screenStream: MediaStream,
audioStream: MediaStream
) => {
setStartingRecording(true);
try {
const res = await getVideoId();
videoId.current = res;
} catch (error) {
console.log(error);
return;
}
const outputStream = new MediaStream();
outputStream.addTrack(screenStream.getVideoTracks()[0]);
outputStream.addTrack(audioStream.getAudioTracks()[0]); // Add audio track
const mimeTypes = [
"video/webm;codecs=h264",
"video/webm;codecs=vp9",
"video/webm;codecs=vp8",
"video/webm",
"video/mp4",
];
let selectedMimeType = "";
for (const mimeType of mimeTypes) {
if (MediaRecorder.isTypeSupported(mimeType)) {
selectedMimeType = mimeType;
break;
}
}
if (!selectedMimeType) {
console.error("No supported mime type found");
return;
}
const videoRecorderOptions = {
mimeType: selectedMimeType,
};
let chunkIndex = 0;
const startNewRecording = () => {
// Stop the current recorder if it's running
if (
videoRecorderRef.current &&
videoRecorderRef.current.state === "recording"
) {
videoRecorderRef.current.stop();
}
// Create a new MediaRecorder instance
const newVideoRecorder = new MediaRecorder(
outputStream,
videoRecorderOptions
);
videoRecorderRef.current = newVideoRecorder;
newVideoRecorder.ondataavailable = async (event) => {
if (event.data.size > 0) {
chunkIndex++;
totalSegments.current++;
const segmentIndex = totalSegments.current;
console.log(event.data);
handleUpload({ segmentIndex, chunk: event.data });
}
};
// Start recording with a 3-second interval
newVideoRecorder.start();
};
// Start the first recording
startNewRecording();
// Set up an interval to restart the recording every 3 seconds
recordingIntervalIdRef.current = setInterval(() => {
startNewRecording();
}, 3000);
setIsRecording(true);
setStartingRecording(false);
};
这在很大程度上就是它的设计工作原理,为了实现高效的视频压缩,您需要关键帧,后跟大量仅描述差异的增量帧。
MediaRecorder 允许调整这些关键帧之间的间隔(或帧计数),作为媒体记录器选项的一部分。 您仍然需要连接 blob 以确保它们以关键帧开始。