如何使用 MATLAB 生成声音?

信息处理 matlab fft 信号分析
2022-01-27 02:45:44

我想使用采样频率等于 20500 Hz 的 MATLAB 生成和播放频率为 100 Hz 和 200 Hz 的音调分别持续 10 秒和 5 秒。

我也想绘制它们的频谱。是否可以使用 MATLAB 做到这一点?

1个回答

应该做这样的事情。请记住,可以通过对信号进行窗口化、对频谱使用分贝标度、仅取频谱的前半部分等来进一步改进此代码。这都是装饰性的东西,你可以自己做(或者我会在某个时候编辑这个答案)。

%% 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);

除了回放它还会产生:

在此处输入图像描述