I have directories that each have several short (~10 second) .avi videos. Does anybody know how I can concatenate all of the videos in a specific directory in alphabetical order to form one single video?
I would try to use VLC, but I have to do this for over a thousand different directories. I didn't realize this would be so difficult, but not able to find anything on Google.
More specifics:
For each directory I want to perform this action on, all videos are guaranteed to be:
.avi,MJPG,20fps,640x480 resolution,no audio,between less than 1 second to 15 seconds long
I'd like the single video file to play just as if I played the individuals back-to-back.
If there's any other specifics I missed please let me know.
The combined videos are intended to all be put into the same directory and given to another person to perform their own video processing on with Matlab. They'll be doing something with either crosscorrelation or machine learning to try and identify a particular object in the videos.
You can use a combination of the VideoReader and VideoWriter (see doc for more examples). Iterate through your video files in alphabetical order and "stream" them into a new file.
I threw together some (untested) code. I have no idea how fast this is, though:
cd(VIDEO_DIRECTORY);
tmp = dir('*.avi'); % all .avi video clips
videoList = {tmp.name}'; % sort this list if necessary! sort(videoList) might work
% create output in seperate folder (to avoid accidentally using it as input)
mkdir('output');
outputVideo = VideoWriter(fullfile(workingDir,'output/mergedVideo.avi'));
% if all clips are from the same source/have the same specifications
% just initialize with the settings of the first video in videoList
inputVideo_init = VideoReader(videoList{1}); % first video
outputVideo.FrameRate = inputVideo_init.FrameRate;
open(outputVideo) % >> open stream
% iterate over all videos you want to merge (e.g. in videoList)
for i = 1:length(videoList)
% select i-th clip (assumes they are in order in this list!)
inputVideo = VideoReader(videoList{i});
% -- stream your inputVideo into an outputVideo
while hasFrame(inputVideo)
writeVideo(outputVideo, readFrame(inputVideo));
end
end
close(outputVideo) % << close after having iterated through all videos
Related
I've just started learning to code for a few months, so I'm sorry if I'm not clear on how I ask my question:
I have different .wav files of synthesized syllables. I have to concatenate them randomly, but they can't be next to each other so they can't be immediately repeated one after another.
Right now I'm not even sure on how to do the first step which is reading the files. I used:
audios = dir('*.wav');
But with this, I'm having trouble extracting the syllables because they are saved in a struct array. So I tried:
samples = [1,.25*Fs];
[ba, fs]=audioread ('ba_2.wav',samples);
[bi, fs]=audioread ('bi_2.wav',samples);
[bo, fs]=audioread ('bo_2.wav',samples);
With all the 48 files (one by one), and I don't think this is efficient, but I read that using eval or a loop to assining names to variables is not a good idea. And by this way I can easily concatenate them like this:
p1=[ba;bi;bo];
But after this I'm stuck, because they have to be randomly repeated in a 2 minute loop. I don't know if maybe there's another way to save my syllables so I can better manipulate them, or what I must do.
I really appreciate your help, I haven't advanced in 2 weeks T-T
This may be an implementation. It, unfortunately, uses a loop that may or may not fit your needs. Within the loop, each audio file .wav is read and concatenated to a complete song called in this example Audio_File. The function randperm() is used to create a random array that can be used to index the structure and concatenate the audio files .wav in random order. In this example I use the variable song which can be representative of syllable.
Method 1: Reading and Concatenating as a Single Audio Array
No regard to duration, only concatenates the .wav files randomly.
Audio_Info = dir('*.wav');
Number_Of_Audio_Files = length(Audio_Info);
%Creating a random array used for random indexing%
Random_Array = randperm(Number_Of_Audio_Files);
%Reading in the first song%
Audio_File = audioread(Audio_Info(Random_Array(1)).name);
for Index = 2: Number_Of_Audio_Files
Random_Index = Random_Array(Index);
%Reading in new song from structure%
Song = audioread(Audio_Info(Random_Index).name);
%Concantenating newly read song%
Audio_File = vertcat(Audio_File,Song);
end
%Playing back the audio%
Audio_Properties = audioinfo(Audio_Info(1).name);
Fs = Audio_Properties.SampleRate;
sound(Audio_File,Fs);
Method 2: Reading Files and Playing within Loop for 2 Minutes
Plays .wav files for approximately 2 minutes randomly. Does not trim last .wav file played if it overflows 2 minutes. Any .wav file played will be executed before 2 minutes. This overflow scenario can be accommodated but depending on your length of the .wav files and your application this might not be crucial. The variable Total_Duration shown below is used to keep track of how long the audio has been playing. The function audioinfo() was used to retrieve the sampling frequency that is later used for playback.
Audio_Info = dir('*.wav');
Number_Of_Audio_Files = length(Audio_Info);
%Grabbing audio properties%
Audio_Properties = audioinfo(Audio_Info(1).name);
Fs = Audio_Properties.SampleRate;
Random_Index = 0;
Total_Duration = 0;
Duration_In_Seconds = 120;
while(Total_Duration < Duration_In_Seconds)
Random_Array = randperm(Number_Of_Audio_Files);
while(Random_Array(1) == Random_Index)
Random_Array = randperm(Number_Of_Audio_Files);
end
Random_Index = Random_Array(1);
%Reading in new song from structure%
Song = audioread(Audio_Info(Random_Index).name);
sound(Song,Fs);
Audio_Properties = audioinfo(Audio_Info(Random_Index).name);
Song_Duration = Audio_Properties.Duration;
Total_Duration = Total_Duration + Song_Duration;
pause(Song_Duration);
end
Ran using MATLAB R2019b
I'm a novice MATLAB user, so apologies if the question is very basic. I need a .wav sound file to be played in a single, specific channel -- let's say the left channel. As it is, my code reads in the sound file, and I add in a column of zeros to nullify the channel I don't want, like so:
currentDir = pwd;
soundFile = [currentDir '\sound1.wav']; % load the file
[y, Fs] = audioread(soundFile); % read the file in
soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = 0; % nullifies the right channel
sound = audioplayer(soundData,Fs);
play(sound);
As it stands, the code currently produces a sound that is full volume in the left speaker, and half volume (but still very much audible) in the right speaker. I have tried this with at least 20 .wav files, with the same result.
In case it's relevant, this happens even when I write in code that explicitly matches the length of the sound variable in 0s, like so:
[y, Fs] = audioread(soundFile);
silentChannel = zeros(size(y));
soundData(:,1) = y(:,1); % keeps sound for the left channel
soundData(:,2) = silentChannel(:,2); % nullifies the right channel
Does anybody know what I'm doing wrong, or have any thoughts?
Your code is definitely correct and it should only play audio in the left channel. I suspect that the problem is caused by a sound-card/driver issues. Allow me suggest the following troubleshooting steps:
Save your output as a wav file using audiowrite('output.wav', soundData, Fs). Play this using a different audio player, such as Audacity. If you still hear output in both channels, it must be a sound-card/driver issue.
Assuming that you are using a Windows PC (going by the syntax in your file path), make sure all sound enhancements are disabled. How to do this depends on the PC. If there is a third-party app controlling the playback settings, you'd have to use that. Otherwise find the settings shown in the picture below in the Control Panel.
In MatLab the expected method for playing sound is the method sound(data,Fs)
To control the channel the sound emits on, you'll want to know how sound() reads data.
data is a matrix with the columns representing channels, and with the rows holding the samples of the waveform for a given sampling fequency Fs
here is a simple implementation.
function treismanwolfe()
close all
clear all
clc
Fs = 40000;
tau = 2*pi();
t = 0:tau/(Fs-1):tau/2;
left = sin(t).*(sin(t*200)+sin(t*1600));
left= left/max(abs(left));
left = left'; %turn column vector into row
right = sin(t).*(sin(t*800)+sin(t*400));
right= right/max(abs(right));
right = right'; %turn column vector into row
data = [left,right*0]; %multiply either by 0 to nullify
sound(data,Fs); %so you can hear it.
end
I hope this works for you. Enjoy!
When I run your code the audio output is only audible in the left channel as you have specified.
#Austin Kootz' version with the sound()-function is just as good and also produces what you're looking for, but with audioplayer-object you have the ability to stop the playback in the middle of the playback (as you probably know)
Have you tried converting your .wav to another format to see if that makes a change?
I'm trying to extract information from a sound file in order to use it in a video classification algorithm I'm working on.
My problem is that I don't know how to work exactly with audio files in Matlab.
Below is what I need to accomplish:
open the audio file and get the sampling rate/frequency
I need to work on a window of 2 seconds so I have to loop over the file and get each 2 seconds as a window and then do the ftt (Fast-Fourier-Transform) on each window.
After that it is my turn to use these values to do what I want
any help would be appreciated
Thanks.
Following code may only give you some idea. You may need to determine another fft size, a windowing function like hamming etc.
To read a wav file:
[data, Fs] = wavread('path.wav');
Splitting to 2 sec windows and getting fft:
frameFFT = [];
timeStep = Fs*2;
for i=1:timeStep:length(data)-timeStep
frameFFT = [frameFFT; fft(data(i:i+timeStep-1),1024)];
end
I would like to record a continuous video in Matlab until some other flag changes, allowing matlab to continue performing other tasks during video acquisition (like deciding whether or not the flag should be set). Since these recordings could last upwards of 3 hours, perhaps closing the recording every hour, writing to a file video_1, then recording for another hour and dumping to video_2, etc for as long as the flag isn't set. However, from what I've seen using Matlab's Image Processing Toolbox, you have to specify some kind of number of frames to capture, or frames per trigger, etc. I'm not really too sure how to proceed.
Some simple code to record video I have is:
% create video obj
video = videoinput('winvideo',1);
% create writer obj
writerObj = VideoWriter('output.avi');
% set video properties
video.LoggingMode = 'disk';
video.DiskLogger = writerObj;
% start recording video
start(video);
% wait
wait(video, inf)
% save video
close(video.DiskLogger);
delete(video);
clear video;
However, the output video is only .3 seconds long. I've followed the following tutorial to get a 30 second recording down to a 3 second video available here but I can't figure out how to make it go on continuously.
Any help would be appreciated!
aviObject = avifile('myVideo.avi'); % Create a new AVI file
for iFrame = 1:100 % Capture 100 frames
% ...
% You would capture a single image I from your webcam here
% ...
F = im2frame(I); % Convert I to a movie frame
aviObject = addframe(aviObject,F); % Add the frame to the AVI file
end
aviObject = close(aviObject); % Close the AVI file
source: How do I record video from a webcam in MATLAB?
I searched the internet and stack overflow but could not find a solution or even helpful hints to my problem.
I need to write a specialised video annotation software in MATLAB which has to be capable to play multiple videos (at least 2) simultaneously on a GUI. The video files are XVID-encoded. Up to now, I basically just adjusted the mathworks.com example for video playback (xylophon.avi, see movie() description).
I am familiar with the mmreader, VideoReader, movie and implay functions but still I am facing two issues:
Even if I read in only a small number of frames (like in the xylophon.avi example), my progam soon exceeds available memory. Also, it takes quite long to read in even relatively few frames (say 100).
The movie() function is sycnhronous, so the second video does not start until the first video completed. How can I call two movie()-functions concurrently? Or is there another way to show two (or more) videos simultaneously?
Any suggestions? Thanks!
First of all MATLAB is not multithreaded. Doing two things in parallel will be difficult. Try to breakout to Java. Matlab uses JIDE as their graphical front-end which is built on Swing. Use MATLAB Builder JA in order to compile your MATLAB code to Java, or add your own 'Panels' to the IDE as shown in this question.
You could display the videos in two different windows and start the playback simultaneously by giving the videos a handle and calling its undocumented play function. This removes any struggle you might have with videos of unequal length as well.
handle1 = implay('file1.mp4');
handle2 = implay('file2.mp4');
handle1.Parent.Position = [100 100 640 480];
handle2.Parent.Position = [740 100 640 480];
play(handle1.DataSource.Controls)
play(handle2.DataSource.Controls)
In principle, you can display each video frame as an image and alternate updating each video, but getting it to play at exactly the right frame rate might be difficult.
Try something like the following. This probably won't work as-is, but you should be able to update it.
v1 = VideoReader(firstVideo)
v2 = VideoReader(secondVideo)
i1 = 0;
i2 = 0;
while i1 < v1.NumberOfFrames && i2 < v2.NumberOfFrames
if i1 < v1.NumberOfFrames
i1 = i1+1;
subplot(1,2,1)
image(v1.read(i1))
end
if i2 < v2.NumberOfFrames
i2 = i2+1;
subplot(1,2,2)
image(v2.read(i2))
end
drawnow
end