Combining video files in matlab

70 views (last 30 days)
Cole
Cole on 22 Jun 2021
I want to use vision.VideoFileReader to combine 2 video files in matlab. Essentially, I have 2 videos which are 24:10 and 23:35 long each, where I want to append them together to make one video which should be 47:45 long. I have previously looked at VideoWriter and VideoReader and found them to be comparatively slow. However, I still am encountering a challenge in combining 2 videos. The resulting video from the code yielded a video which is a little over 24:33 long, and the filesize is now massive. I have pasted my code below.
vfr = vision.VideoFileReader('LLZO0024-04-21-24.MP4', 'AudioOutputPort',false);
vfw = vision.VideoFileWriter('LLZO0024-04-21-24_comb.avi', 'FileFormat','AVI', 'AudioInputPort',false, ...
'FrameRate',vfr.info.VideoFrameRate);
%Write the first of the two videos to a new file
while ~isDone(vfr)
[frame, audio] = vfr();
vfw(frame);
end
release(vfr);
%release the first video, and begin to write the second video to file.
vfr = vision.VideoFileReader('LLZO0024-04-21-24_2.MP4', 'AudioOutputPort',false);
while ~isDone(vfr)
[frame, audio] = vfr();
vfw(frame);
end
release(vfr);
release(vfw);
  1 Comment
Mohammad Sami
Mohammad Sami on 23 Jun 2021
unless there is a specific reason to use matlab for this, i would suggest use a dedicated video processing software to join the two clips. there are free software available for this purpose. ffmpeg and vlc can also do this job.

Sign in to comment.

Answers (1)

Alamanda Ponappa Poovaya
Alamanda Ponappa Poovaya on 11 Nov 2021
Edited: Alamanda Ponappa Poovaya on 11 Nov 2021
You can use while loops with the "hasFrame" check to write each frame of each video to the new file. Below is an example with two "MPEG-4" video files. Please note that the video frames in each video must be the same frame size but do not have to be the same length.
% Set up parameters
Vid1 = VideoReader('MyVideo1.mp4'); % Video 1
Vid2 = VideoReader('MyVideo2.mp4'); % Video 2
v = VideoWriter('MergedVideo','MPEG-4'); % Create new video file
open(v)
% Iterate on all frames in video 1 and write one frame at a time
while hasFrame(Vid1)
Video1 = readFrame(Vid1); % read each frame
writeVideo(v,Video1) % write each frame
end
% Iterate again in video 2
while hasFrame(Vid2)
Video2 = readFrame(Vid2);
writeVideo(v,Video2)
end
close(v)
Refer to this answer as well, it talks about the same problem

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by