3
$\begingroup$

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?

$\endgroup$
5
$\begingroup$

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

$\endgroup$
  • $\begingroup$ Why is the amplitude of 100Hz is bigger the 200Hz, is it affect by the duration (5s and 10s)? $\endgroup$ – user20694 Apr 25 '16 at 4:41
  • $\begingroup$ @rubievozĐỗAnhTú Please read the question once again carefully and notice the durations of signals. One of them is switched off after 5 seconds. $\endgroup$ – jojek Apr 25 '16 at 6:58

protected by jojek Apr 25 '16 at 6:55

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.