我写了这段代码:
def plotWaveforms(audioFile1, audioFile2, imageFile, startSegment=30, endSegment=35, amp1=0.5, amp2=0.5):
# Load audio files
y1, sr1 = librosa.load(audioFile1, sr=None, offset=startSegment, duration=endSegment - startSegment)
y2, sr2 = librosa.load(audioFile2, sr=None, offset=startSegment, duration=endSegment - startSegment)
# Normalize and adjust the amplitude of the audio signals
y1 = normalize_audio(y1, amp1)
y2 = normalize_audio(y2, amp2)
# Create a figure with a black background
plt.figure(figsize=(16, 1), facecolor='black')
# Plot the second audio file as a filled waveform
plt.fill_between(np.linspace(0, len(y2) / sr2, len(y2)), y2, color='green', alpha=1)
# Plot the first audio file as a filled waveform
plt.fill_between(np.linspace(0, len(y1) / sr1, len(y1)), y1, color='blue', alpha=0.5)
# Remove axes, labels, and title for a clean look
plt.axis('off')
# Save the figure with a specific resolution
plt.savefig(imageFile, format='png', dpi=300, bbox_inches='tight', pad_inches=0)
plt.close()
产生这个:
但我试图使用每个点的峰值或定期间隔绘制一条填充曲线,如下所示:
我该怎么做?
您可以使用
argrelextrema
中的 scipy.signal
来获取最小值或最大值的索引。这是一个小教程:
import pandas as pd
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelextrema
fs = 44000 # 44 kHz
duration = 10 # seconds
N = int(fs * duration) # get number of samples
t = np.linspace(0, duration, N) # generate time vector
f = 1000 # 1 kHz
a = np.log(0.01) / duration # decay
y = np.exp(a * t) * np.sin(2 * np.pi * f * t) # generate signal
y = pd.Series(y, index=t) # as a series
minimaIdx = argrelextrema(y.values, np.less)[0] # get index of minima
maximaIdx = argrelextrema(y.values, np.greater)[0] # get index of maxima
minima = y.iloc[minimaIdx] # get minima
maxima = y.iloc[maximaIdx] # get maxima
plt.plot(y, label='Dampened Sine Function') # plot the signal
plt.plot(minima, "-o", color='red', label='Local Minima') # the manima
plt.plot(maxima, "-s", color='green', label='Local Maxima') # and the maxima
# add decorations...
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Dampened Sine Function with Local Extrema')
plt.legend()
plt.grid()
这就是它的样子:
要填写最大值和 0 之间的值,您可以使用这个简单的插图:
plt.figure()
plt.fill_between(maxima.index, 0, maxima.values, color='lightblue', label='Area between 0 and Maxima')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('Area Under Maxima')
plt.legend()
plt.grid()
你会得到这个:
我之前已经用音频信号做过这个,它应该工作得很好。希望这有帮助!