Applications of Audio System Toolbox Using MATLAB
The Audio System Toolbox in MATLAB provides algorithms and tools for designing, simulating, and analyzing audio processing systems. This section demonstrates how to use the toolbox for various audio-related tasks, including filtering, noise reduction, and audio signal generation.
Basic Concepts of Audio Processing using Matlab
The toolbox includes objects and functions for audio input/output, visualization, and processing. For instance, you can create audio filters, simulate reverberation, or analyze the frequency spectrum of signals.
Fundamental Audio Processing Operations in Matlab
1. Generating and Playing Audio Signals
Here’s how to generate a simple sine wave and play it:
% Generating a sine wave signal
fs = 44100; % Sampling frequency
t = 0:1/fs:2; % Time vector for 2 seconds
f = 440; % Frequency of sine wave (A4 note)
sineWave = sin(2*pi*f*t); % Sine wave formula
sound(sineWave, fs); % Play the sound
2. Visualizing an Audio Signal
To analyze the waveform of an audio signal, use the plot
function:
% Plotting the waveform of a sine wave
plot(t, sineWave);
xlabel('Time (s)');
ylabel('Amplitude');
title('Sine Wave');
grid on;
3. Applying a Low-Pass Filter
Filters are essential for noise reduction or isolating specific frequency components. Here’s an example of applying a low-pass filter:
% Applying a low-pass filter
d = designfilt('lowpassiir', 'FilterOrder', 8, 'PassbandFrequency', 500, 'SampleRate', fs);
filteredSignal = filter(d, sineWave);
sound(filteredSignal, fs); % Play the filtered signal
4. Frequency Spectrum Analysis
To analyze the frequency components of a signal, use the Fast Fourier Transform (FFT):
% Computing and plotting the FFT of a signal
N = length(sineWave);
fftSignal = fft(sineWave);
fAxis = (0:N-1)*(fs/N); % Frequency axis
plot(fAxis, abs(fftSignal));
xlabel('Frequency (Hz)');
ylabel('Magnitude');
title('Frequency Spectrum');
grid on;
5. Reading and Writing Audio Files
To handle audio files, the toolbox provides audioread
and audiowrite
functions:
% Reading and writing an audio file
[y, fs] = audioread('input.wav'); % Read the audio file
sound(y, fs); % Play the audio
audiowrite('output.wav', y, fs); % Write to a new file
Advanced Example Problems for Audio Processing
Example 1: Noise Reduction in Audio Signals
Remove noise from an audio signal using a band-pass filter and analyze the results.
% Noise Reduction using Band-Pass Filter
[y, fs] = audioread('noisy_audio.wav'); % Load noisy audio
d = designfilt('bandpassiir', ...
'FilterOrder', 8, ...
'HalfPowerFrequency1', 300, ...
'HalfPowerFrequency2', 3400, ...
'SampleRate', fs); % Design band-pass filter
filteredAudio = filter(d, y); % Apply the filter
sound(filteredAudio, fs); % Play the cleaned audio
audiowrite('filtered_audio.wav', filteredAudio, fs); % Save the output
% Visualize the waveform before and after filtering:
% Plotting the original and filtered signals
t = (0:length(y)-1)/fs; % Time vector
subplot(2,1,1);
plot(t, y);
title('Original Noisy Audio');
xlabel('Time (s)'); ylabel('Amplitude');
grid on;
subplot(2,1,2);
plot(t, filteredAudio);
title('Filtered Audio');
xlabel('Time (s)'); ylabel('Amplitude');
grid on;
Example 2: Creating a Reverberation Effect
Simulate room reverberation using an audio effect object.
% Adding Reverberation Effect
[y, fs] = audioread('dry_audio.wav'); % Load a dry audio file
reverb = reverberator('PreDelay', 50, ...
'DecayFactor', 0.5, ...
'WetDryMix', 0.3); % Create reverberation object
reverbAudio = reverb(y); % Apply the effect
sound(reverbAudio, fs); % Play the audio with reverb
audiowrite('reverb_audio.wav', reverbAudio, fs); % Save the output
Example 3: Designing a Graphic Equalizer
Create a graphic equalizer to adjust specific frequency bands of an audio signal.
% Graphic Equalizer Example
[y, fs] = audioread('music.wav'); % Load an audio file
bands = [100, 500, 1000, 5000, 10000]; % Center frequencies
gains = [3, -2, 5, 0, -1]; % Gain adjustments (dB)
equalizedAudio = y; % Initialize the processed audio
for i = 1:length(bands)
d = designfilt('bandpassiir', ...
'FilterOrder', 8, ...
'HalfPowerFrequency1', bands(i)*0.8, ...
'HalfPowerFrequency2', bands(i)*1.2, ...
'SampleRate', fs); % Design a band filter
bandSignal = filter(d, y); % Filter the band
equalizedAudio = equalizedAudio + bandSignal * (10^(gains(i)/20)); % Apply gain
end
sound(equalizedAudio, fs); % Play the equalized audio
audiowrite('equalized_audio.wav', equalizedAudio, fs); % Save the output
Example 4: Speech-to-Text Analysis
Use speech recognition to transcribe spoken audio into text.
% Speech-to-Text Example
[y, fs] = audioread('speech.wav'); % Load a speech audio file
speechObject = speechClient('Google', 'languageCode', 'en-US'); % Create a speech client
results = speechObject.recognize(y, fs); % Perform speech recognition
disp('Transcribed Text:');
disp(results.Transcript); % Display the recognized text
Example 5: Synthesizing Audio Effects
Generate an audio signal and apply multiple effects such as distortion and chorus.
% Applying Distortion and Chorus Effects
fs = 44100; % Sampling frequency
t = 0:1/fs:2; % Time vector for 2 seconds
f = 440; % Frequency of base tone
sineWave = sin(2*pi*f*t); % Generate a sine wave
distortedSignal = sineWave .* 2; % Apply distortion
chorusEffect = audioDeviceWriter('SampleRate', fs); % Initialize chorus effect
chorusSignal = chorusEffect(distortedSignal);
sound(chorusSignal, fs); % Play the processed signal
audiowrite('chorus_signal.wav', chorusSignal, fs); % Save the output
Example 6: Pitch Shifting
Modify the pitch of an audio signal without changing its duration.
% Pitch Shifting Example
[y, fs] = audioread('speech.wav'); % Load an audio file
pitchShifter = pitchShifter('SemitoneShift', 5); % Create a pitch shifter object (shift up by 5 semitones)
shiftedAudio = pitchShifter(y); % Apply pitch shifting
sound(shiftedAudio, fs); % Play the shifted audio
audiowrite('pitch_shifted_audio.wav', shiftedAudio, fs); % Save the output
Example 7: Analyzing Spectrograms
Generate and analyze the spectrogram of an audio signal.
% Spectrogram Analysis
[y, fs] = audioread('music.wav'); % Load audio file
window = hamming(256); % Define a Hamming window
overlap = 128; % Define overlap between segments
nfft = 512; % FFT points
spectrogram(y, window, overlap, nfft, fs, 'yaxis'); % Generate spectrogram
title('Spectrogram of Audio Signal');
The spectrogram helps visualize the frequency content of the audio signal over time.
Example 8: Voice Activity Detection (VAD)
Detect when a person is speaking in an audio file.
% Voice Activity Detection (VAD)
[y, fs] = audioread('speech_with_pauses.wav'); % Load audio file
vad = voiceActivityDetector('SampleRate', fs); % Create VAD object
speechDetected = vad(y); % Detect speech activity
disp('Speech Activity Detected (1 = speech, 0 = no speech):');
disp(speechDetected); % Display detected speech frames
This technique is useful for speech processing applications where non-speech parts need to be ignored.
Example 9: Real-Time Audio Processing
Capture audio from a microphone, apply a filter, and play it back in real time.
% Real-Time Audio Filtering
audioReader = audioDeviceReader('SampleRate', 44100, 'SamplesPerFrame', 1024); % Input device
audioWriter = audioDeviceWriter('SampleRate', 44100); % Output device
bpFilter = designfilt('bandpassiir', ...
'FilterOrder', 8, ...
'HalfPowerFrequency1', 300, ...
'HalfPowerFrequency2', 3400, ...
'SampleRate', 44100); % Design band-pass filter
disp('Processing audio in real-time... Press Ctrl+C to stop.');
while true
audioIn = audioReader(); % Read from microphone
audioOut = filter(bpFilter, audioIn); % Apply filter
audioWriter(audioOut); % Play filtered audio
end
This example demonstrates how to process audio data in real time using MATLAB.
Example 10: Generating White Noise and Adding to Audio
Generate white noise and mix it with an audio signal for testing purposes.
% Adding White Noise to Audio
[y, fs] = audioread('speech.wav'); % Load clean audio
noise = 0.01 * randn(size(y)); % Generate white noise
noisySignal = y + noise; % Add noise to the signal
sound(noisySignal, fs); % Play noisy audio
audiowrite('noisy_audio.wav', noisySignal, fs); % Save the noisy audio
% Plot the original and noisy signals
t = (0:length(y)-1) / fs;
subplot(2,1,1); plot(t, y);
title('Original Signal');
xlabel('Time (s)'); ylabel('Amplitude'); grid on;
subplot(2,1,2); plot(t, noisySignal);
title('Noisy Signal');
xlabel('Time (s)'); ylabel('Amplitude'); grid on;
Example 11: Detecting Peaks in an Audio Signal
Identify peaks in an audio signal, such as drum beats in music.
% Peak Detection in Audio Signal
[y, fs] = audioread('drum_loop.wav'); % Load an audio file
t = (0:length(y)-1) / fs; % Time vector
[peaks, locs] = findpeaks(y, 'MinPeakHeight', 0.5, 'MinPeakDistance', fs*0.1); % Detect peaks
plot(t, y);
hold on;
plot(locs/fs, peaks, 'ro'); % Mark detected peaks
title('Peak Detection in Audio Signal');
xlabel('Time (s)'); ylabel('Amplitude'); grid on;
Example 12: Audio Delay Effect
Create a delay effect for an audio signal.
% Audio Delay Effect
[y, fs] = audioread('guitar.wav'); % Load audio
delayTime = 0.3; % Delay time in seconds
delaySamples = round(delayTime * fs);
delayedSignal = [zeros(delaySamples, 1); y]; % Add delay
outputSignal = y + 0.5 * delayedSignal(1:length(y)); % Mix original with delayed
sound(outputSignal, fs); % Play the delayed audio
audiowrite('delayed_audio.wav', outputSignal, fs); % Save the output
Useful MATLAB Functions for Audio Processing
Practice Problems
Test Yourself
1. Generate a square wave of 440 Hz and play it for 3 seconds.
2. Design a high-pass filter to remove frequencies below 300 Hz from a signal.
3. Compute the spectrogram of an audio signal using the spectrogram
function.