When recording video from USB cameras, using a timer can lead to inaccuracies in the video duration. Timers in MATLAB can be unreliable if the system is busy, you may learn more about the limitations of the “timer” function in the official documentation: https://www.mathworks.com/help/releases/R2022b/matlab/ref/timer.html.
As a workaround, you can rely on the frame rates of your cameras to control the recording time. For the basic scenario where both cameras have the same frame rate, such as 30 fps in your case, you can use a simple for loop to capture frames for the desired duration:
for i = 1:(100 * video_1.FrameRate)
% Call “snapshot” and “writeVideo” same as before
end
For cases where the frame rates differ, such as 24 fps and 30 fps, you can use a time-based loop to synchronize the frame captures accurately:
% Time step size based on the maximum frame rate
timeStep = 1 / max(frameRate1, frameRate2);
% Error threshold for floating-point comparison
errThreshold = 1e-4;
% Duration for capturing video in seconds
captureDuration = 100;
for t = 0:timeStep:captureDuration - timeStep
if abs(mod(t, 1 / frameRate1)) < errThreshold
I1 = snapshot(cam1);
writeVideo(video_1, I1);
end
if abs(mod(t, 1 / frameRate2)) < errThreshold
I2 = snapshot(cam2);
writeVideo(video_2, I2);
end
end