blender.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. #!/usr/bin/env python
  2. """
  3. An audio synthesis library for Python.
  4. It makes heavy use of the `itertools` module.
  5. Good luck! (This is a work in progress.)
  6. """
  7. import sys
  8. import math
  9. import wave
  10. import struct
  11. import random
  12. import argparse
  13. from itertools import count, islice
  14. try:
  15. from itertools import zip_longest
  16. except ImportError:
  17. from itertools import imap as map
  18. from itertools import izip as zip
  19. from itertools import izip_longest as zip_longest
  20. try:
  21. stdout = sys.stdout.buffer
  22. except AttributeError:
  23. stdout = sys.stdout
  24. # metadata
  25. __author__ = 'Zach Denton'
  26. __author_email__ = 'zacharydenton@gmail.com'
  27. __version__ = '0.3'
  28. __url__ = 'http://github.com/zacharydenton/wavebender'
  29. __longdescr__ = '''
  30. An audio synthesis library for Python.
  31. '''
  32. __classifiers__ = [
  33. 'Topic :: Multimedia :: Sound/Audio :: Sound Synthesis'
  34. ]
  35. def grouper(n, iterable, fillvalue=None):
  36. "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
  37. args = [iter(iterable)] * n
  38. return zip_longest(fillvalue=fillvalue, *args)
  39. def sine_wave(frequency=440.0, framerate=44100, amplitude=0.5,
  40. skip_frame=0):
  41. '''
  42. Generate a sine wave at a given frequency of infinite length.
  43. '''
  44. if amplitude > 1.0: amplitude = 1.0
  45. if amplitude < 0.0: amplitude = 0.0
  46. for i in count(skip_frame):
  47. sine = math.sin(2.0 * math.pi * float(frequency) * (float(i) / float(framerate)))
  48. yield float(amplitude) * sine
  49. def square_wave(frequency=440.0, framerate=44100, amplitude=0.5):
  50. for s in sine_wave(frequency, framerate, amplitude):
  51. if s > 0:
  52. yield amplitude
  53. elif s < 0:
  54. yield -amplitude
  55. else:
  56. yield 0.0
  57. def damped_wave(frequency=440.0, framerate=44100, amplitude=0.5, length=44100):
  58. if amplitude > 1.0: amplitude = 1.0
  59. if amplitude < 0.0: amplitude = 0.0
  60. return (math.exp(-(float(i%length)/float(framerate))) * s for i, s in enumerate(sine_wave(frequency, framerate, amplitude)))
  61. def white_noise(amplitude=0.5):
  62. '''
  63. Generate random samples.
  64. '''
  65. return (float(amplitude) * random.uniform(-1, 1) for i in count(0))
  66. def compute_samples(channels, nsamples=None):
  67. '''
  68. create a generator which computes the samples.
  69. essentially it creates a sequence of the sum of each function in the channel
  70. at each sample in the file for each channel.
  71. '''
  72. return islice(zip(*(map(sum, zip(*channel)) for channel in channels)), nsamples)
  73. def write_wavefile(f, samples, nframes=None, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048):
  74. "Write samples to a wavefile."
  75. if nframes is None:
  76. nframes = 0
  77. w = wave.open(f, 'wb')
  78. w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))
  79. max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)
  80. # split the samples into chunks (to reduce memory consumption and improve performance)
  81. for chunk in grouper(bufsize, samples):
  82. frames = b''.join(b''.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None)
  83. w.writeframesraw(frames)
  84. w.close()
  85. def write_pcm(f, samples, sampwidth=2, framerate=44100, bufsize=2048):
  86. "Write samples as raw PCM data."
  87. max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)
  88. # split the samples into chunks (to reduce memory consumption and improve performance)
  89. for chunk in grouper(bufsize, samples):
  90. frames = b''.join(b''.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None)
  91. f.write(frames)
  92. f.close()
  93. def main():
  94. parser = argparse.ArgumentParser(prog="wavebender")
  95. parser.add_argument('-c', '--channels', help="Number of channels to produce", default=2, type=int)
  96. parser.add_argument('-b', '--bits', help="Number of bits in each sample", choices=(16,), default=16, type=int)
  97. parser.add_argument('-r', '--rate', help="Sample rate in Hz", default=44100, type=int)
  98. parser.add_argument('-t', '--time', help="Duration of the wave in seconds.", default=60, type=int)
  99. parser.add_argument('-a', '--amplitude', help="Amplitude of the wave on a scale of 0.0-1.0.", default=0.5, type=float)
  100. parser.add_argument('-f', '--frequency', help="Frequency of the wave in Hz", default=440.0, type=float)
  101. parser.add_argument('filename', help="The file to generate.")
  102. args = parser.parse_args()
  103. # each channel is defined by infinite functions which are added to produce a sample.
  104. channels = ((sine_wave(args.frequency, args.rate, args.amplitude),) for i in range(args.channels))
  105. # convert the channel functions into waveforms
  106. samples = compute_samples(channels, args.rate * args.time)
  107. # write the samples to a file
  108. if args.filename == '-':
  109. filename = stdout
  110. else:
  111. filename = args.filename
  112. write_wavefile(filename, samples, args.rate * args.time, args.channels, args.bits // 8, args.rate)
  113. if __name__ == "__main__":
  114. main()