生成一个Python代码 文件浏览框选择指定wav文件并绘制1/3倍频程结果,并封装成函数或者类。
时间: 2024-02-21 13:59:06 浏览: 106
好的,以下是代码实现:
```python
import tkinter as tk
import tkinter.filedialog as fd
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
class WavPlotter:
def __init__(self):
self.filepath = ""
self.fs = 0
self.data = []
self.fig, self.ax = plt.subplots()
def browse_file(self):
self.filepath = fd.askopenfilename(filetypes=[("WAV Files", "*.wav")])
if self.filepath:
self.ax.clear()
self.ax.set_title(self.filepath)
self.ax.set_xlabel("Time (s)")
self.ax.set_ylabel("Amplitude")
self.fs, self.data = wavfile.read(self.filepath)
self.ax.plot(np.arange(len(self.data))/self.fs, self.data)
self.plot_third_octave_bands()
def plot_third_octave_bands(self):
freqs = np.array([1, 1.25, 1.6, 2, 2.5, 3.15, 4, 5, 6.3, 8, 10, 12.5, 16, 20, 25, 31.5, 40, 50, 63, 80, 100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000, 20000])
third_octave_bands = np.array([125, 160, 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000, 20000])
band_indices = np.array([np.argmin(np.abs(freqs - f)) for f in third_octave_bands])
fft = np.abs(np.fft.fft(self.data))
freqs = np.fft.fftfreq(len(self.data), 1/self.fs)
band_amplitudes = []
for i in range(len(band_indices)-1):
band_amplitudes.append(np.mean(fft[band_indices[i]:band_indices[i+1]]))
band_amplitudes.append(np.mean(fft[band_indices[-1]:]))
self.ax.plot(third_octave_bands, band_amplitudes, "o", color="red")
def run(self):
root = tk.Tk()
root.title("WAV File Plotter")
browse_button = tk.Button(root, text="Browse", command=self.browse_file)
browse_button.pack()
self.ax.set_xlim(0, 10)
self.ax.set_ylim(-2**15, 2**15)
self.ax.grid()
self.ax.axhline(0, color="black", lw=1)
canvas = plt.gcf().canvas
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
root.mainloop()
if __name__ == "__main__":
wp = WavPlotter()
wp.run()
```
这是一个名为`WavPlotter`的类,它包含了一个浏览文件的函数`browse_file()`和一个绘制1/3倍频程结果的函数`plot_third_octave_bands()`,并在运行时通过`run()`函数创建了一个GUI窗口。其中,`browse_file()`函数使用了`tkinter`模块创建了一个文件浏览框,选择.wav文件后,该函数会读取.wav文件并在GUI窗口中绘制出其波形图和1/3倍频程结果。`plot_third_octave_bands()`函数使用了`numpy`和`matplotlib`模块计算和绘制1/3倍频程结果。
你可以将该类的代码复制到Python文件中,并在需要时实例化该类并调用`run()`函数即可。
阅读全文