请注意注释掉的代码:逐个包络比对就不能加窗了。
import librosa
import numpy as np
from scipy.signal import windows
import matplotlib.pyplot as plt
# 读取音频文件
audio_file = 'sine.wav'
signal, sample_rate = librosa.load(audio_file, sr=None, mono=False)
# 检查通道数并处理信号
if signal.ndim > 1:
num_channels = signal.shape[0]
print(f"音频文件有 {num_channels} 个通道")
# 如果是4通道,取第X个通道进行处理,这里示例取第4个通道(索引为3)
if num_channels == 2:
signal = signal[0, :]
else:
# 如果信号是单通道,直接使用
print("音频文件是单通道")
# 计算每个周期的采样点数
cycle_samples = int(sample_rate / 1000)
# # 创建汉宁窗
# window_length = cycle_samples * 1 # 窗长度为10个周期
# window = windows.hann(window_length)
# # 对信号的开头和结尾分别应用汉宁窗
# windowed_signal = signal.copy()
# windowed_signal[:window_length//2] *= window[:window_length//2]
# windowed_signal[-window_length//2:] *= window[window_length//2:]
# 计算周期数
num_cycles = len(signal) // cycle_samples
# 存储异常周期的时间点和幅值
anomaly_times = []
anomaly_amplitudes = []
# 逐个周期比较包络
for i in range(num_cycles - 1):
start = i * cycle_samples
end = (i + 1) * cycle_samples
current_cycle = signal[start:end]
next_cycle = signal[end:end+cycle_samples]
# 计算当前周期和下一个周期的包络差异
diff = np.abs(current_cycle - next_cycle)
# 如果差异大于阈值,则认为是异常周期
if np.max(diff) > 0.1:
anomaly_time = start / sample_rate
anomaly_times.append(anomaly_time)
anomaly_amplitudes.append(np.max(np.abs(current_cycle)))
# 打印异常周期的时间点和幅值
for time, amplitude in zip(anomaly_times, anomaly_amplitudes):
print(f"异常周期时间点: {time:.3f}s, 幅值: {amplitude:.3f}")
# 绘制时域波形图
time = np.arange(len(signal)) / sample_rate
plt.figure(figsize=(8,4))
plt.plot(time, signal, label='Signal')
# 标注异常周期
for t in anomaly_times:
plt.axvline(x=t, color='r', linestyle='--', label='Anomaly Detected')
plt.xlabel('Time(s)')
plt.ylabel('Amplitude')
plt.title('Windowed Waveform with Anomalies Highlighted')
plt.legend()
plt.show()