一个输出Sine Sweep Wave文件的Python程序

   1 # this porgram output sine sweep wave file
   2 # HYRY Studio 2007/01/17
   3 
   4 from math import *
   5 from time import clock
   6 import array
   7 import wave
   8 import psyco
   9 psyco.profile()
  10 
  11 def sinesweep(f0, f1, sweeptime, samplingrate, peak):
  12     k = exp(log(float(f1)/f0)/sweeptime)
  13     data = array.array("h", "\x00"*sweeptime*samplingrate*2)
  14     dt = 1.0/samplingrate
  15     t = 0.0
  16     p = 2*pi*f0/log(k)
  17     for i in xrange(sweeptime*samplingrate):
  18         data[i] = int(peak*sin( p*(pow(k,t)-1) ))
  19         t += dt
  20     return data
  21 
  22 def sindata(f0, time, samplingrate, peak):
  23     data = [int(peak*sin(2*pi*f0*x/samplingrate)) for x in xrange(int(time*samplingrate))]
  24     return array.array("h", data)
  25 
  26 if __name__ =="__main__":
  27     SAMPLING_RATE = 44100
  28     SWEEP_TIME = 50
  29     F0 = 20
  30     F1 = 20000
  31     PEAK = 0x2000
  32     start = clock()
  33     data = sinesweep(F0, F1, SWEEP_TIME, SAMPLING_RATE, PEAK)
  34     print clock() - start
  35     f = wave.open("sweep.wav","wb")
  36     f.setnchannels(1) # mono wave
  37     f.setsampwidth(2) # 16bit
  38     f.setframerate(SAMPLING_RATE) #sampling rate
  39     f.setnframes((6+SWEEP_TIME)*SAMPLING_RATE)
  40     f.setcomptype("NONE","NONE")
  41     f.writeframes("\x00" * 2 * 2 * SAMPLING_RATE)
  42     f.writeframes(sindata(1000, 0.1, SAMPLING_RATE, 0x6000).tostring())
  43     f.writeframes("\x00" * int(2 * 1.9 * SAMPLING_RATE))
  44     f.writeframes(data.tostring())
  45     f.writeframes("\x00" * 2 * 2 * SAMPLING_RATE)
  46     f.close()

1. 反馈