How to cut audio file into segments?

조회 수: 12 (최근 30일)
Lara Lirnow
Lara Lirnow 2017년 2월 5일
답변: Rahul 2025년 1월 3일
I have an audio file (.wav) which I need to cut into segments. Segments (start and stop values) are stored in cell array C. I managed to get values only from one cell to cut the sound file, but I don't know how to get one by one values from cell array C and parallel cut the sound signal. Intervals in the text file look like this:
0.300000 0.410000 ,0.41000 0.430000 ,0.95000 0.990000 ,1.21500 1.260000 ,...
In cell array C every interval is in it's own cell -
'0.300000 0.410000', '0.41000 0.430000' , ...
I have this code:
[data,Fs] = audioread('sound.wav');
list = fopen('intervals.txt','r');
for k=1:length(list)
content = fgets(list)
C= strsplit(content,',')% splits str at the delimiters specified by delimiter
nums = C{1,k} % gets only data from the first cell
x = str2num(nums) %convert from char to numeric value
for n=1:length(x)
start=x(1)
stop=x(2)
N = length(data);
totaldur = N/Fs; % total duration
t = linspace(0,totaldur,N); % create a time vector
%logical indexing
seg1 = data(t>start & t<stop)
sound(seg1) %play the segment
end
end

답변 (1개)

Rahul
Rahul 2025년 1월 3일
As per the code shared, in order to apprpriately cut the audio signal into segments as per the specified list of intervals, consider indexing the data in the following way:
[data, Fs] = audioread('sound.wav');
list = {'0.300000 0.410000', '0.41000 0.430000' , ...}
for k = 1:length(list)
interval = list{k};
x = str2num(interval);
if length(x) == 2
start = x(1);
stop = x(2);
startIdx = max(1, floor(start * Fs));
stopIdx = min(length(data), ceil(stop * Fs));
segment = data(startIdx:stopIdx); % Indexing appropriately taking Fs(Sampling frequency) into account
sound(segment, Fs); % Fs(Sampling frequency) helps in obtaining the correct aound output.
end
end
The following MATLAB Answer and Mathworks documentations can be referred to know more:
Hope this helps! Thanks.

카테고리

Help CenterFile Exchange에서 Audio and Video Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by