Python
import numpy as np
import [Link] as plt
import [Link] as wavfile
# Load the audio and convert to mono if stereo.
fs, audio_data = [Link]('gearbox_vibration.wav')
if audio_data.ndim > 1:
audio_data = [Link](audio_data, axis=1)
# Normalize the signal to the range [-1, 1].
audio_data = audio_data / [Link]([Link](audio_data))
# Plot the first 0.1 s of the waveform.
time_axis = [Link](0, len(audio_data)) / fs
end_index = int(0.1 * fs)
[Link]()
[Link](time_axis[:end_index], audio_data[:end_index])
[Link]('Time (s)')
[Link]('Amplitude')
[Link]('First 0.1s of the Waveform')
[Link]()
[Link]()
# Compute and plot the single-sided magnitude spectrum up to Fs/3 Hz.
n_fft = len(audio_data)
fft_result = [Link](audio_data, n=n_fft)
fft_magnitude = [Link](fft_result) / n_fft
frequencies = [Link](n_fft, 1/fs)
single_sided_magnitude = 2 * fft_magnitude[:n_fft//2]
single_sided_frequencies = frequencies[:n_fft//2]
max_freq_index = [Link](single_sided_frequencies <= fs/3)[0][-1]
[Link]()
[Link](single_sided_frequencies[:max_freq_index],
single_sided_magnitude[:max_freq_index])
[Link]('Frequency (Hz)')
[Link]('Magnitude')
[Link]('Single-Sided Magnitude Spectrum up to Fs/3 Hz')
[Link]()
[Link]()
# Identify and print the frequency with the highest magnitude (excluding DC).
start_index = [Link](single_sided_frequencies > 0)[0][0]
peak_frequency_index = [Link](single_sided_magnitude[start_index:max_freq_index])
peak_frequency = single_sided_frequencies[start_index + peak_frequency_index]
print(f'The frequency with the highest magnitude (excluding DC) is: {peak_frequency:.2f} Hz')