Python--生成Wav格式文件

1、下载与安装scipy

scipy下载链接: http://www.scipy.org/Download#head-0dfc04e10313d2e70988c6cb3bef7a9e09860c8f

同时可以下载说明文档链接http://docs.scipy.org/doc/


2、wav文件写操作



3、signal.chirp函数使用说明



4、点击按钮实现信号生成,点击按钮实现信号显示




5、Python代码

#!usr/bin/env python
#code=utf-8

from Tkinter import *
import wave
import numpy as np
import scipy.signal as signal
import matplotlib.pyplot as plt
import sys

sys.setrecursionlimit(1000000)

#define the params of wave
channels = 1
sampwidth = 2
framerate = 9600
file_name = 'sweep.wav'
frequency_begin = 1
frequency_end = 100
#define the time of wave
time = 1

def Generate_Wav():
	#generate the time bar
	t = np.arange(0,time,1.0/framerate)
	#generate the chirp signal from 300 to 3300Hz
	wave_data = signal.chirp(t, frequency_begin, time, frequency_end, method = 'linear')*1000
	#cast to the type of short
	wave_data = wave_data.astype(np.short)
	#open a wav document
	f = wave.open(file_name,"wb")
	#set wav params
	f.setnchannels(channels)
	f.setsampwidth(sampwidth)
	f.setframerate(framerate)
	#turn the data to string
	f.writeframes(wave_data.tostring())
	f.close()

def my_button(root,label_text,button_text,button_func):  
    '''''function of creat label and button'''  
    #label details  
    label = Label(root)  
    label['text'] = label_text  
    label.pack()  
    #label details  
    button = Button(root)  
    button['text'] = button_text  
    button['command'] = button_func  
    button.pack()

def read_wave_data(file_path):  
    #open a wave file, and return a Wave_read object  
    f = wave.open(file_path,"rb")  
    #read the wave's format infomation,and return a tuple  
    params = f.getparams()  
    #get the info  
    nchannels, sampwidth, framerate, nframes = params[:4]  
    #Reads and returns nframes of audio, as a string of bytes.   
    str_data = f.readframes(nframes)  
    #close the stream  
    f.close()  
    #turn the wave's data to array  
    wave_data = np.fromstring(str_data, dtype = np.short)   
    time = np.arange(0, nframes) * (1.0/framerate)  
    return wave_data, time

def Plot_Wav():
	wave_data, time = read_wave_data(file_name)
	plt.plot(time, wave_data)
	plt.grid(True)
	plt.show()

def main():
	root = Tk()
	my_button(root, 'Generate a sweep wav', 'Generate', Generate_Wav)
	my_button(root, 'Plot the wav', 'Plot', Plot_Wav)
	root.mainloop()

if __name__ == "__main__":
	main()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值