#!/usr/bin/env python
# -*- coding: utf-8 -*-
#http://blog.csdn.net/myhaspl
#code:[email protected]
import wave
import pylab as pl
import numpy as np print 'http://blog.csdn.net/myhaspl'
print '[email protected]'
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.pi
for curpos in xrange(0,nframes):
possamp=np.sin((curpos/samplepercycle)*maxcycle)
sampleval=int(max_amplitude*possamp)
wave_data[curpos]=sampleval str_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.pi
for 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, 2
wave_data = wave_data.T
new_wave_data.shape = -1, 2
new_wave_data = new_wave_data.T
time = 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()
本博客所有内容是原创,未经书面许可,严禁任何形式的转载
http://blog.csdn.net/u010255642
python 产生声音的正弦波并叠加
>>> runfile(r'K:\book_prog\audio_hy.py', wdir=r'K:\book_prog')
http://blog.csdn.net/myhaspl
[email protected]
working...
generate wav data....
save new wav files....