1.20131007 Image or Sound-generating Loop

From Media Design: Networked & Lens-Based wiki
Jump to navigation Jump to search

1.吡————!

  import wave , struct

  filename = "mmm.wav"
  nframes=0
  nchannels=1
  sampwidth=2 # 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)

 
  freq = 220

  cycle = framerate / freq
 
 
  data = ''
  for i in range(20):
      for x in range(200):


          data += struct.pack('h', int(0.1 * max_amplitude))
      for x in range(200):
          data += struct.pack('h', int(-0.1 * max_amplitude))
 
  w.writeframesraw(data)
 
  w.close()

File:Mmm-1.ogg

2.failed :only generate a silent wav file.

import wave, struct
  import struct from math import sin,pi,pow
 
  max_amplitude = 32767
  sample_rate = 44100
  duration_sec = 3
  sample_len = sample_rate*duration_sec
  filename = 'hei.wav'
  print "creating sound file:",filename
  print "sample rate:",sample_rate
  print "duration(sec):",duration_sec
  print "# samples",sample_len
  wavefile = wave.open(filename, 'w')
  wavefile.setparams((2,2,sample_rate,0,'none','not compressed'))
  samples = []
 
  for i in range(sample_len):
        t = float(i) / sample_rate
        sample = max_amplitude*sin(t*320*2*pi)
 
       #print i, t, sample
       packed_sample = struct.packed_sample('h', sample)
       samples.append(packed_sample)
       samples.append(packed_sample)
 
  sample_str = ''.join(samples)	
  wavefile.writeframes(sample_str)
  wavefile.close()
  print "done writing file."