赞
踩
测试音响系统的通路上是否有外部干扰时,可以通过播放1000赫兹的正弦波信号,在输出端采集数字信号(I2S,TDD,A2B)并保存为.wav文件。 然后通过以下Python代码检测。
import numpy as np
import librosa
import matplotlib.pyplot as plt
def load_and_normalize_audio(audio_path, sr=48000, apply_window=True, channel=2):
"""channel参数指定要分析的声道,索引从0开始"""
y, sr = librosa.load(audio_path, sr=sr, mono=False)
# 确保选取多声道中的指定声道,如果是单声道信号,则直接使用
if y.ndim > 1 and y.shape[0] > channel:
y = y[channel, :]
elif y.ndim > 1:
print("Warning: Requested channel not found. Using first channel instead.")
y = y[0, :]
# 先归一化音频信号到[-1, 1]
y = y / np.max(np.abs(y))
# 应用窗函数
if apply_window:
window = np.hanning(len(y))
y = y * window
return y, sr
def find_interference(y, sr, target_freq, threshold_db=-80):
"""分析音频,找出除目标频率外的干扰信号"""
# 计算FFT
Y = np.fft.rfft(y)
freqs = np.fft.rfftfreq(len(y), d=1/sr)
# 计算幅度(dBFS)
Y_amplitude = np.abs(Y) / len(Y)
Y_dbfs = 20 * np.log10(np.maximum(Y_amplitude, 1e-12))
# 将目标频率附近的幅度设置为非常低的数值来忽略目标频率
target_idx = np.abs(freqs - target_freq).argmin()
ignore_band = 10 # 忽略目标频率附近±10Hz范围
Y_dbfs[target_idx-ignore_band:target_idx+ignore_band] = -np.inf
# 寻找最大幅度的干扰频率
max_idx = np.argmax(Y_dbfs)
# 检查干扰是否高于阈值
if Y_dbfs[max_idx] > threshold_db:
print(f"检测到干扰频率:{freqs[max_idx]}Hz,幅度 {Y_dbfs[max_idx]}dB")
else:
print("未检测到显著干扰。")
def plot_spectrum(y, sr):
"""绘制频谱图"""
Y = np.fft.rfft(y)
freqs = np.fft.rfftfreq(len(y), d=1/sr)
Y_amplitude = np.abs(Y) / len(Y)
Y_dbfs = 20 * np.log10(np.maximum(Y_amplitude, 1e-12))
plt.figure(figsize=(10, 6))
plt.plot(freqs, Y_dbfs)
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude (dB)')
plt.title('Frequency Spectrum')
plt.ylim(-120, 0)
plt.xlim(0, sr // 2)
plt.show()
# 替换audio_path为你的音频文件路径
audio_path = 'sine.wav'
y, sr = load_and_normalize_audio(audio_path)
plot_spectrum(y, sr)
find_interference(y, sr, target_freq=1000)
以上代码由AI生成,本人调试完成,实测可用! :)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。