Hey Syed,
I understand that your query is to create a MATLAB App that lets you record a video while also showing you the preview of what is recorded within the app.
To achieve this, we can createa a private property that holds a webcam object. This object can then be used to both preview the video onto a UIAxes component while also being used by the Video Writer to write the video to video file.
The following code demonstrates this approach:
classdef recorder < matlab.apps.AppBase
% Properties that correspond to app components
properties (Access = public)
% Component Properties
end
properties (Access = private)
cam % Camera Object
isRecording logical = false % Track the recording state
videoWriter % Video Writer Object
timer
end
methods (Access = public)
function updateLiveFeed(app)
frame = snapshot(app.cam);
image(app.UIAxes, frame);
drawnow; % Update UI
% Write frame to video if recording
if app.isRecording
writeVideo(app.videoWriter, frame);
end
end
end
% Callbacks that handle component events
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
% Initialize webcam and timer
app.cam = webcam;
app.timer = timer('ExecutionMode', 'fixedRate', 'Period', 1/60, ...
'TimerFcn', @(~,~) updateLiveFeed(app));
start(app.timer);
end
% Button pushed function: RecordButton
function RecordRecordButtonPushed(app, event)
if ~app.isRecording
% Start recording
app.isRecording = true;
app.RecordButton.Text = 'Stop';
% Initialize video writer
app.videoWriter = VideoWriter('recordedVideo.avi');
open(app.videoWriter);
else
% Stop recording
app.isRecording = false;
app.RecordButton.Text = 'Record';
% Release video writer
close(app.videoWriter);
end
end
end
% Component initialization
methods (Access = private)
% Create UIFigure and components
end
end
The app interface should look as follows:
Once you record a video, you can see it show up in the same directory as the app:
You can refer to the documentation of Video Writer below:
Also, to use the webcam, ensure that you have MATLAB Support Package for USB Webcams Add On package installed. You can find the link to the Add On below: