How can I verify my code ?

3 views (last 30 days)
John
John on 6 Jan 2022
Answered: Altaïr on 24 Mar 2025
This is my code :
Fs = 16000;Channels = 1; bits = 16;
r= audioread('myWAVaudiofile.wav');
duration = 3;
sound (r,Fs,bits);
t = 0:1/Fs:(length(r)-1)/Fs;
subplot (2,1,1); plot (t,r,'LineWidth',1.5);
xlabel('time (sec)'); ylabel('Amplitude');
title('Time Domain plot of the Signal');
n = length (r); F = 0 :(n-1)*Fs/n;
Y = fft(r,n);
F_0 = (-n/2:n/2-1).*(Fs/n);
Y_0 = fftshift(Y);
AY_0 = abs(Y_0);
subplot(2,1,2); plot(F_0,AY_0,'LineWidth',1.5);
xlabel('Frequency (Hz)'); ylabel('Amplitude');
title('Frequency Domain Plot Of Audio Signal');
How can I :
-Verify that that 12000" sample is indeed occurring at 0.75 sec spot.
-Verify the spectral spacing.
-What is the frequency (in Hz) at k = 8000 and k = 3000.

Answers (1)

Altaïr
Altaïr on 24 Mar 2025
Hey @John,
In MATLAB R2021b, various types of unit tests, such as script, function, or class-based tests, can be utilized to validate code, all of which fall under the Testing Frameworks in MATLAB. More detailed information is available here: https://www.mathworks.com/help/releases/R2021b/matlab/matlab-unit-test-framework.html.
  • Script-based unit tests: These involve writing tests in separate sections of a script file to perform basic qualifications, access diagnostics, and customize test runs using a TestRunner object.
  • Function-based unit tests: Tests are written as local functions in a test file, following the xUnit philosophy, and include advanced features like constraints, tolerances, and diagnostics.
  • Class-based unit tests: Tests are written as methods in a class file, offering full framework access, shared fixtures, parameterized tests, and content reuse.
Here's how a function based unit test might look like for the first two tests in the query:
function tests = testAudioAnalysis
tests = functiontests(localfunctions);
end
function testSampleOccurrence(testCase)
Fs = 16000;
r = audioread('sample-15s.wav');
t = 0:1/Fs:(length(r)-1)/Fs;
% Verify that the 12000th sample occurs at 0.75 seconds
sampleIndex = 12000;
expectedTime = 0.75; % seconds
actualTime = t(sampleIndex);
testCase.verifyEqual(actualTime, expectedTime, 'AbsTol', 1e-4);
end
function testSpectralSpacing(testCase)
Fs = 16000;
r = audioread('sample-15s.wav');
n = length(r);
% Calculate frequency resolution
freqResolution = Fs / n;
% Verify spectral spacing
expectedSpacing = 0.0189;
testCase.verifyEqual(expectedSpacing, freqResolution, 'AbsTol', 1e-4);
end
For more details on these tests, the following pages can be referenced:

Categories

Find more on Audio I/O and Waveform Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!