#!/usr/bin/env python # -*- coding: utf-8 -*-#http://blog.csdn.net/myhaspl #code:myhaspl@qq.com import waveimport pylab as plimport numpy as npprint 'http://blog.csdn.net/myhaspl' print 'myhaspl@qq.com' print print 'working...' print "generate wav data...."# 打开WAV文档fo = wave.open(r"plpl1.wav", "wb")# 设置波形参数#采样率framerate = 22050#声道数nchannels=2#每位宽度sampwidth=2#长度nframes =framerate#频率freq=440#最大振幅max_amplitude = 4000#每样本秒数interval=1.0/freq#每周期样本数samplepercycle=interval*framerate#=interval/(1/framerate)wave_data=np.zeros((nframes), dtype=np.short)maxcycle=2*np.pifor curpos in xrange(0,nframes): possamp=np.sin((curpos/samplepercycle)*maxcycle) sampleval=int(max_amplitude*possamp) wave_data[curpos]=samplevalstr_data=wave_data.tostring()#频率freq=880#最大振幅max_amplitude = 2000#每样本秒数interval=1.0/freq#每周期样本数samplepercycle=interval*framerate#=interval/(1/framerate)new_wave_data=np.zeros((nframes), dtype=np.short)maxcycle=2*np.pifor curpos in xrange(0,nframes): possamp=np.sin((curpos/samplepercycle)*maxcycle) sampleval=int(max_amplitude*possamp) new_wave_data[curpos]=sampleval# 绘制波形wave_data.shape = -1, 2wave_data = wave_data.Tnew_wave_data.shape = -1, 2new_wave_data = new_wave_data.Ttime = np.arange(0, nframes/2)[:100]# * (1.0 / framerate)pl.subplot(323)pl.plot(time, new_wave_data[0][:100])pl.subplot(324)pl.plot(time, new_wave_data[1][:100], c="g")pl.xlabel("time (seconds)")#波形叠加new_wave_data+=wave_data# 绘制波形time = np.arange(0, nframes/2)[:100]# * (1.0 / framerate)pl.subplot(321)pl.plot(time, wave_data[0][:100])pl.subplot(322)pl.plot(time, wave_data[1][:100], c="g")pl.xlabel("time (seconds)")time = np.arange(0, nframes/2)[:100]# * (1.0 / framerate)pl.subplot(325)pl.plot(time, new_wave_data[0][:100])pl.subplot(326)pl.plot(time, new_wave_data[1][:100], c="g")pl.xlabel("time (seconds)")#写波形数据参数print "save new wav files...."new_str_data=new_wave_data.tostring()fo.setnchannels(nchannels)fo.setframerate(framerate)fo.setsampwidth(sampwidth)fo.setnframes(nframes)fo.writeframes(new_str_data)fo.close()
本博客所有内容是原创,未经书面许可,严禁任何形式的转载
python 产生声音的正弦波并叠加
>>> runfile(r'K:\book_prog\audio_hy.py', wdir=r'K:\book_prog')
http://blog.csdn.net/myhaspl myhaspl@qq.com working... generate wav data.... save new wav files....