声信号1/3倍频程python代码结果通过gui画出
时间: 2024-02-22 12:55:40 浏览: 175
abc.rar_1/3 倍频程_1/3倍频_1/3倍频程_matlab 1/3倍频程_倍频程 matlab
5星 · 资源好评率100%
以下是一个简单的 Python 代码,可以绘制声音信号的 1/3 倍频程图形界面(GUI):
```python
import numpy as np
import matplotlib.pyplot as plt
import tkinter as tk
from tkinter.filedialog import askopenfilename
def open_file():
filename = askopenfilename()
return filename
def get_audio_data(filename):
# Load audio file
audio_data, sampling_rate = librosa.load(filename, sr=None, mono=True)
# Compute the magnitude spectrogram
stft = np.abs(librosa.stft(audio_data, n_fft=2048, hop_length=512))
# Compute the 1/3-octave band frequencies
fmin = 20
fmax = sampling_rate / 2
freqs = librosa.core.octave_bins(fmin, fmax, bins_per_octave=3)
# Compute the 1/3-octave band magnitudes
bands = librosa.feature.melspectrogram(
sr=sampling_rate, S=stft**2, n_mels=len(freqs),
fmin=freqs[0], fmax=freqs[-1]
)
# Convert to dB scale
bands_db = librosa.power_to_db(bands, ref=np.max)
return freqs, bands_db
def plot_audio_data(freqs, bands_db):
# Create a new plot
plt.clf()
fig, ax = plt.subplots()
# Plot the 1/3-octave band magnitudes
ax.plot(freqs, bands_db.T, alpha=0.7)
# Set the x-axis to log scale
ax.set_xscale('log')
# Set the axis labels
ax.set_xlabel('Frequency (Hz)')
ax.set_ylabel('Magnitude (dB)')
# Set the plot title
ax.set_title('1/3-Octave Spectrum')
# Show the plot
plt.show()
# Create a GUI window
root = tk.Tk()
# Add a button to open a file
open_button = tk.Button(root, text='Open', command=lambda: plot_audio_data(*get_audio_data(open_file())))
open_button.pack()
# Run the GUI loop
root.mainloop()
```
该代码使用了 `librosa` 库来加载音频文件并计算其 1/3 倍频程。在 GUI 中,用户可以通过打开文件按钮来选择要绘制的音频文件。一旦文件被选择,代码将计算 1/3 倍频程并将其绘制在一个新的图形窗口中。用户可以在窗口中查看图像并进行缩放和导出。
阅读全文