# Segment audio file using time

54 views (last 30 days)
Melissa Ette on 27 Oct 2020 at 1:55
Answered: Mathieu NOE on 28 Oct 2020 at 8:44
I have a .wav file ( song.wav ) that is 5s long, I have time_start= 3.23s and time_end=4.35s and another sing.wav that is 4s long with time_start1=2.38s and time_-end1=3.56s. I want to store the segments of song.wav and sing.wav that start respectively are time_start and time_start1 and end at time_end and time_end1 into a cell array. How do I start? The answer I've seen so far were cutting the file in terms of Fs, that's not it

Mathieu NOE on 27 Oct 2020 at 8:58
hello Melissa
you have to do the computation on samples , and you have to know the sampling frequency FS for each wav file
or
then determine start and stop indexes , knowing the start and stop times
song1_start_ind = round(start_time*FS); % must be an integer value
song1_stop_ind = round(stop_time*FS); % must be an integer value
then
song1_extract = song1(song1_start_ind:song1_stop_ind);
do the same on the second wav file :
song2_extract = song2(song2_start_ind:song2_stop_ind);
to save to a cell array :
C{1} = song1_extract;
C{2} = song2_extract;
Mario Malic on 27 Oct 2020 at 9:21
Hi Mathieu,
It would be great if you post this in an answer section.
Mathieu NOE on 27 Oct 2020 at 18:26
will do !
tx

Mathieu NOE on 27 Oct 2020 at 18:26
hello Melissa
you have to do the computation on samples , and you have to know the sampling frequency FS for each wav file
or
then determine start and stop indexes , knowing the start and stop times
song1_start_ind = round(start_time*FS); % must be an integer value
song1_stop_ind = round(stop_time*FS); % must be an integer value
then
song1_extract = song1(song1_start_ind:song1_stop_ind);
do the same on the second wav file :
song2_extract = song2(song2_start_ind:song2_stop_ind);
to save to a cell array :
C{1} = song1_extract;
C{2} = song2_extract;

#### 1 Comment

Melissa Ette on 27 Oct 2020 at 19:40
Thank you so much! How would this work in a loop? I am now trying to do it for a bigger sample

Mathieu NOE on 28 Oct 2020 at 8:44
hi
this is waht i suggest to do on one single wav file
if it matches your request , the main code can be converted to a function , then you can also create a loop for looping through multiple wav files in your directory. Let me know if this is also of interest for you.
so for the time being, single file / multiple extracts demo :
% or
% create list of start / stop time indexes
start_time = [1; 2 ; 3 ; 4]; % length is equal of nb of extracts
stop_time = [5; 6 ; 7 ; 9];
% main loop %
for ci = 1:length(start_time)
% determine start and stop indexes , knowing the start and stop times
song_start_ind = round(start_time(ci)*FS); % must be an integer value
song_stop_ind = round(stop_time(ci)*FS); % must be an integer value
% then extract
song_extract = song(song_start_ind:song_stop_ind);
% save to a cell array :
C{ci} = song_extract;
% % check (plot)
% figure(ci) , plot(song_extract);
end