Matlab - problem with snr function

9 次查看(过去 30 天)
jnc
jnc 2021-11-12
评论: dpb 2021-11-12
I have to add noise to recorded audio, so as SNR of result signal should be equal 3dB.
The idea is to calculate SNR of recorded audio and generated gaussian noise. According to that ratio I want to scale noise and then add it to recorded audio
I convert file to vector using audioread function:
[ y, fsampl] = audioread('123.wav');
And then I generate gaussian noise:
noise = normrnd(0,1,1,length(y));
Next I want to calculate signal to noise ratio using snr() function:
cur_snr= snr(y, noise);
But i get an error:
Error using snr
Expected input number 2, Fs, to be a scalar.
Error in snr>timeSNR (line 187)
validateattributes(fs,{'numeric'},{'real','finite','scalar','positive'}, ...
Error in snr (line 157)
[r, noisePow] = timeSNR(plotType, harmType, Args{:});
Error in untitled4 (line 10)
cur_snr= snr(y, noise);
I have no idea what can be wrong. What i checked:
-audio file is read corectly
-noise and y vector has the same length

采纳的回答

dpb
dpb 2021-11-12
The two inputs have to have the same orientation as well as same length.
You've created a row vector above for the noise while undoubtedly the input signal y is a column vector.
I just checked here and that is the error message you get in that case -- it's not very informative relative to the cause of the error: TMW could have done better in either dealing with the inputs as it finds them inside the function or at least providing a meaningful error message.
Use
noise = normrnd(0,1,size(y));
instead to make the two commensurate in size automagically.
  2 个评论
dpb
dpb 2021-11-12
I've got another bug report to submit after the precision issue with datetime and duration and nsec resolution; I'll add an enhancement request on snr as well -- at least fix the error message if not handle vectors of different orientations silently.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2021-11-12
This works fine:
[y, fs] = audioread('guitartune.wav');
subplot(3, 1, 1);
plot(y, 'b-');
grid on;
title('Perfect Signal', 'FontSize', 20)
noiseAmplitude = 0.05 * max(y)
noise = noiseAmplitude * normrnd(0,1,1, length(y));
% Make a column vector like y
noise = noise(:);
subplot(3, 1, 2);
plot(noise, 'b-');
grid on;
title('Noise Alone', 'FontSize', 20)
% Create noisy signal
noise_y = y + noise;
subplot(3, 1, 3);
plot(noise_y, 'b-');
grid on;
cur_snr= snr(y, noise)
caption = sprintf('Noisy Signal. SNR = %.2f', cur_snr);
title(caption, 'FontSize', 20)

类别

Help CenterFile Exchange 中查找有关 Acoustics, Noise and Vibration 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by