Friday 8 January 2016

fft - How do I generate sound using MATLAB?


I want to generate and play sound for tones with frequency 100 Hz and 200 Hz for 10 sec and 5 sec respectively using MATLAB with sampling frequency equal to 20500 Hz.


Also I want to plot their frequency spectrum. Is it possible to do this using MATLAB?



Answer



Something like that should do. Please keep in mind that this code can be further improved by windowing your signal, using decibel scale for spectrum, taking only first half of a spectrum, etc. This is all cosmetic stuff and you can do it on your own (or maybe I will edit this answer at some point).


%% Time domain parameters
fs = 20500; % Sampling frequency
dt = 1/fs; % Time resolution
T = 10; % Signal duration

t = 0:dt:T-dt; % Total duration
N = length(t); % Number of time samples

%% Signal generation
f0_1 = 100; % fundamental frequency of first sinusoid
f0_2 = 200; % fundamental frequency of second sinusoid
x1 = sin(2*pi*f0_1*t); % first sinusoid
x2 = sin(2*pi*f0_2*t); % second sinusoid

% We want 200 Hz signal to last for half of a time, therefore zero-out

% second half - use the logical indexing of time variable
x2(t>5)=0;

% Now add two signals
x = x1+x2;

% Calculate spectrum
X = abs(fft(x))/N;
% Prepare frequency axis
freqs = (0:N-1).*(fs/N);


%% Plotting time and frequency domain
% Time domain signal plot
subplot(211)
plot(t, x)
grid on
xlabel('Time [s]')
ylabel('Amplitude')
title('Time domain signal')


% Spectrum plot
subplot(212)
plot(freqs, X)
grid on
xlim([0 max(freqs)])
xlabel('Frequency [Hz]')
ylabel('Amplitude')
title('Spectrum')

%% Playing back signal

% Normalize the audio:
x = 0.99*x/max(abs(x));

% For MATLAB R2014a use audioplayer
player = audioplayer(x, fs);
play(player)

% For older versions use wavplay
% wavplay(x, fs);


And apart from playing back it will also produce:


enter image description here


No comments:

Post a Comment

readings - Appending 内 to a company name is read ない or うち?

For example, if I say マイクロソフト内のパートナーシップは強いです, is the 内 here read as うち or ない? Answer 「内」 in the form: 「Proper Noun + 内」 is always read 「ない...