定制界面读取wav文件并且绘图(python)

摘要:本文主要使用tkinter定制GUI,使用wave读取wav文件,使用matplotlib绘图。

00 导入所需库

import os
import wave
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
from tkinter import *
from tkinter import filedialog

01 定制GUI

def readwav():
    global ftype
    ftype=filedialog.askopenfilename(title='打开 *.wav',filetypes=[('Sound','*.wav')])
win=Tk()
win.title('技术邻')
b1=Button(win,text='WAV数据',relief='raised',font='宋体 20 bold',width=15,command=readwav)
b1.pack(padx=50,pady=10,side='left')
b2=Button(win,text='分析',relief='raised',font='宋体 20 bold',width=15,
          foreground='purple',background='lightgray',command=win.destroy)
b2.pack(padx=50,pady=20,side='left')
win.mainloop()

定制界面读取wav文件并且绘图(python)的图1

02 读取wav文件

f_name=ftype.split('/')
f_dir='/'.join(f_name[0:-1])
os.chdir(f_dir)
fgs=f_name[-1].split('.')

if fgs[-1]=='wav':
    with wave.open(ftype,'rb') as f:
        params = f.getparams()
        #print(params)
        nchannels, sampwidth, framerate, nframes = params[:4]
    with wave.open(ftype,'rb') as f:
        strData = f.readframes(nframes)
        waveData = np.fromstring(strData,dtype=np.short)
        waveData.shape=-1,nchannels
        xt = np.arange(0,nframes)*(1.0 / framerate)

03 绘图

    fig,ax=plt.subplots(2,1,sharex='all')
    fig.set_size_inches(11.69,8.27)
    fig.set_dpi(200)
    fig.subplots_adjust(hspace=0)
    ax1=ax[0]
    ax1.plot(xt,waveData[:,0],linewidth=0.5)
    ax1.set_ylabel('左声道')
    ax1.set_title('MP3数据')
    ax1.grid(axis='both')
    ax2=ax[1]
    ax2.plot(xt,waveData[:,1],linewidth=0.5)
    ax2.set_ylabel('右声道')
    ax2.grid(axis='both')
    fig.savefig(f_name[-1]+'.jpg')
    fig.show()

定制界面读取wav文件并且绘图(python)的图2

默认 最新
当前暂无评论,小编等你评论哦!
点赞 评论 收藏
关注