Skip to content

Instantly share code, notes, and snippets.

@ibigbug
Created March 23, 2013 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibigbug/5227390 to your computer and use it in GitHub Desktop.
Save ibigbug/5227390 to your computer and use it in GitHub Desktop.
Generate simple.wav using python
#!/usr/bin/env python2
#coding:utf-8
import numpy
import wave
class MainHandler(object):
def __init__(self, duration=10, frequency=2000):
self.output = wave.open('output.wav', 'wb')
self.duration = duration
self.frequency = frequency
self.samplerate = 44100
def _gene_signal(self):
samples = self.duration * self.samplerate
freq = self.frequency
period = self.samplerate / float(freq)
omega = numpy.pi * 2 / period
x = numpy.arange(int(period), dtype=numpy.float) * omega
y = 16384 * numpy.sin(x)
signal = numpy.resize(y, (samples, ))
ret = ''
for i in xrange(len(signal)):
ret += wave.struct.pack('h', signal[i])
return ret
def write(self):
signal = self._gene_signal()
self.output.setparams((1, 2, self.samplerate,
self.samplerate*self.duration,
'NONE', 'noncompressed'))
self.output.writeframes(signal)
self.output.close()
if __name__ == '__main__':
import sys
duration, frequency = sys.argv[1:3]
m = MainHandler(int(duration), int(frequency))
m.write()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment