Reputation: 469
I want to sample an audio signal. I have a wav
file 5 seconds long. I want save samples every 300 ms.
I use function audioread
in MATLAB that read samples containing in file, this is my code:
[signal,fs]=audioread('file.wav');
dt = 1/fs;
N = length(signal);
t = 0:dt:(N-1)*dt;
plot(t,signal)
ms=t*1000;
How can I do save in an array samples that are repeated every 300 ms?
Upvotes: 0
Views: 70
Reputation: 18925
Let's assume your wav
file has a sampling rate of fs = 44100
(which is quite common), i.e. you have 44100
samples per second. Now, you want to have one sample each 0.3 s
. You have to calculate the corresponding number of samples to "skip" with respect to your original sampling rate, i.e. skip = 0.3 * fs = 13230
in this case. Now, you can simply access each skip
'th element in your original signal
(and also time interval t
).
Here's some code to do the work, and visualize the above:
% Artificial data
signal = sin(linspace(0, 2*pi, 5 * 44100));
fs = 44100;
dt = 1 / fs;
N = length(signal);
t = 0:dt:(N-1)*dt;
% "Re-sampling" parameters
dt_new = 0.3;
skip = dt_new * fs;
% Extract every skip'th value from original time interval and signal
t_new = t(1:skip:end).'
signal_new = signal(1:skip:end);
% Some visualization
figure(1);
hold on;
plot(t, signal);
plot(t_new, signal_new, 'r.', 'MarkerSize', 15);
hold off;
We get the following output, the original signal is blue, the red points are the samples at every 0.3 s
:
If you have a look at t_new
, you see, that the sampling points exactly match your desired interval of 0.3 s
:
t_new =
0.00000
0.30000
0.60000
0.90000
1.20000
1.50000
1.80000
2.10000
2.40000
2.70000
3.00000
3.30000
3.60000
3.90000
4.20000
4.50000
4.80000
Hope that helps!
EDIT: There's also a resample
function available in the Signal Processing Toolbox. I'm not sure, if this function is useful here, since the new sampling rate would be fs_new = 1 / 0.3 = 3.3333
, but resample
only accepts integers. Maybe, there's another more sophisticated (toolbox) function to do the job automatically.
Upvotes: 1