User:Elleke Hageman/Python: Sound and Image: Difference between revisions

From XPUB & Lens-Based wiki
No edit summary
Line 1: Line 1:
[[File:Screen Shot.jpg | 640px]]
[[File:Screen Shot.jpg | 640px]]
'''Sound #1'''
import wave, struct
filename = "sound.wav"
nframes=0
nchannels=1
sampwidth=1 # in bytes so 2=16bit, 1=8bit
framerate=44100
bufsize=2048
w = wave.open(filename, 'w')
w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))
max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)
# split the samples into chunks (to reduce memory consumption and improve performance)
#for chunk in grouper(bufsize, samples):
#    frames = ''.join(''.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None)
#    w.writeframesraw(frames)
freq = 15000
# this means that FREQ times a second, we need to complete a cycle
# there are FRAMERATE samples per second
# so FRAMERATE / FREQ = CYCLE LENGTH
cycle = framerate / freq
data = ''
for i in range(10):
    for x in range(20000):
        data += struct.pack('h', int(0.4 * max_amplitude))
    for x in range(1000):
        data += struct.pack('h', int(-0.8 * max_amplitude))
w.writeframesraw(data)
w.close()

Revision as of 11:36, 14 October 2013

Screen Shot.jpg

Sound #1

import wave, struct

filename = "sound.wav" nframes=0 nchannels=1 sampwidth=1 # in bytes so 2=16bit, 1=8bit framerate=44100 bufsize=2048

w = wave.open(filename, 'w') w.setparams((nchannels, sampwidth, framerate, nframes, 'NONE', 'not compressed'))

max_amplitude = float(int((2 ** (sampwidth * 8)) / 2) - 1)

  1. split the samples into chunks (to reduce memory consumption and improve performance)
  2. for chunk in grouper(bufsize, samples):
  3. frames = .join(.join(struct.pack('h', int(max_amplitude * sample)) for sample in channels) for channels in chunk if channels is not None)
  4. w.writeframesraw(frames)

freq = 15000

  1. this means that FREQ times a second, we need to complete a cycle
  2. there are FRAMERATE samples per second
  3. so FRAMERATE / FREQ = CYCLE LENGTH

cycle = framerate / freq


data = for i in range(10):

   for x in range(20000):
       data += struct.pack('h', int(0.4 * max_amplitude))
   for x in range(1000):
       data += struct.pack('h', int(-0.8 * max_amplitude))

w.writeframesraw(data)

w.close()