Clear Filters
Clear Filters

plot an audio file

8 views (last 30 days)
Michael Sugiarto
Michael Sugiarto on 22 Mar 2022
Answered: Aman Banthia on 28 Sep 2023
How do i plot an audio file that shows the measured kHz and also in 20 miliseconds interval? Im using MATLAB r2021b.
My code is now like this
recObj = audiorecorder;
Fs=8000;
filename = sprintf('myAudioData.wav');
disp('Start speaking.')
recordblocking(recObj, 10);
disp('End of Recording.');
%play(recObj);
doubleArray = getaudiodata(recObj);
audiowrite(filename,doubleArray,Fs);
%plot(doubleArray);
%title('Audio Signal (double)');
[x,Fs] = audioread('myAudioData.wav');
[m,n]=size(x);
dt=1/Fs;
t=dt*(0:m-1);
idx = (t>=1.030) & (t<1.032);
selected_t = t(idx);
selected_x = x(idx,:);
plot(selected_t, selected_x);
Thankyou

Answers (1)

Aman Banthia
Aman Banthia on 28 Sep 2023
Hi Michael,
I understand that you are trying to plot an audio file for 20 milliseconds which is recorded in the file itself.
To display the frequency in kHz, you would typically perform a Fourier transform on the audio signal to convert it from the time domain to the frequency domain. Here's how you can modify your code to do this:
% Record and save audio
recObj = audiorecorder;
Fs = 8000;
filename = 'myAudioData.wav';
disp('Start speaking.')
recordblocking(recObj, 10);
disp('End of Recording.');
doubleArray = getaudiodata(recObj);
audiowrite(filename,doubleArray,Fs);
% Read audio
[x,Fs] = audioread('myAudioData.wav');
[m,n]=size(x);
dt=1/Fs;
t=dt*(0:m-1);
% Select the time segment
idx = (t>=1.030) & (t<1.032);
selected_t = t(idx);
selected_x = x(idx,:);
% Plot the time domain signal
subplot(2,1,1);
plot(selected_t, selected_x);
title('Time Domain Signal')
xlabel('Time (s)')
ylabel('Amplitude')
% Perform the Fourier transform
Y = fft(selected_x);
m_sel = length(selected_x);
P2 = abs(Y/m_sel);
P1 = P2(1:m_sel/2+1);
P1(2:end-1) = 2*P1(2:end-1);
f = Fs*(0:(m_sel/2))/m_sel;
% Plot the frequency domain signal
subplot(2,1,2);
plot(f/1000, P1)
title('Frequency Domain Signal')
xlabel('Frequency (kHz)')
ylabel('|P1(f)|')
Refer to the following MATLAB Documentation to know more about Fast Fourier Transform (‘fft’) function:
Hope the above solution helps you.
Best Regards,
Aman Banthia

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!