MATLAB: Cut out scenes from a video

audiovideovideo editingvideoreadervideowriter

Hi everyone. I have a large number of video files to process. What I want to do is extract parts from each video file. For example if I have a 10 minute Video, I want to cut away everything, so that I'm just left with for example minute 5 to 6, and save this as a new video file, with both video and audio!!!
What I did so far is read in the original Video File, split it up into Frames, select the specific frames, and save them as a new file, but that leaves me with no audio.
how can I get the audio as well? or is there possibly an easier way? some already existing function?
Thank you very much!
My code so far:
function [] = extractscene(nameOfFile, beginTime, endTime, SceneClassifier)
inputName = strcat(nameOfFile,'.mp4');
outputName = strcat(nameOfFile,'_',num2str(SceneClassifier),'_',num2str(beginTime),'_',num2str(endTime),'.avi');
a = VideoReader(inputName);
beginFrame = beginTime * a.FrameRate;
endFrame = endTime * a.FrameRate;
vidObj = VideoWriter(outputName);
open(vidObj);
for img = beginFrame:endFrame
b = read(a, img);
writeVideo(vidObj,b)
end
close(vidObj);

Best Answer

vision.VideoFileReader() can read audio and video.
You would loop reading frames and audio. Drop those until you reach the time you want to start. Start outputing. When you reach the end of the time you want, break out of the loop.
Unfortunately there does not appear to be a good way to translate between frame count and time in the case of variable frame rate. Notice https://www.mathworks.com/help/vision/ref/vision.videofilereader.info.html
VideoFrameRate: Frame rate of the video stream in frames per second. The value may vary from the actual frame rate of the recorded video, and takes into consideration any synchronization issues between audio and video streams when the file contains both audio and video content. This implies that video frames may be dropped if the audio stream leads the video stream by more than 1/(actual video frames per second).