shithub: aubio

Download patch

ref: 1e7a8f938c0259f0555b3b21d75333cee052e52b
parent: daa0d5ddb8081b3cc2219fe641e622995b934966
author: Paul Brossier <piem@piem.org>
date: Fri Mar 8 15:26:24 EST 2013

demos/demo_sink_create_woodblock.py: table lookup to improve synthesis

--- a/python/demos/demo_sink_create_woodblock.py
+++ b/python/demos/demo_sink_create_woodblock.py
@@ -1,15 +1,17 @@
 #! /usr/bin/env python
 
 import sys
-from math import sin, pi
+from math import pi, e
 from aubio import sink
-from numpy import array
+from numpy import arange, resize, sin, exp, zeros
 
-if len(sys.argv) != 2:
-    print 'usage: %s <outputfile>' % sys.argv[0]
+if len(sys.argv) < 2:
+    print 'usage: %s <outputfile> [samplerate]' % sys.argv[0]
     sys.exit(1)
 
-samplerate = 44100      # in Hz
+samplerate = 44100 # samplerate in Hz
+if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
+
 pitch = 2200            # in Hz
 blocksize = 256         # in samples
 duration = 0.02         # in seconds
@@ -16,23 +18,36 @@
 
 twopi = pi * 2.
 
-duration = int ( 44100 * duration ) # convert to samples
-attack = 3
+duration = int ( samplerate * duration ) # convert to samples
+attack = int (samplerate * .001 )
+decay = .5
 
-period = int ( float(samplerate) /  pitch )
-sinetone = [ 0.7 * sin(twopi * i/ period) for i in range(period) ] 
-sinetone *= int ( duration / period )
-sinetone = array(sinetone, dtype = 'float32')
+period = float(samplerate) /  pitch
+# create a sine lookup table
+tablelen = 1000
+sinetable = arange(tablelen + 1, dtype = 'float32')
+sinetable = 0.7 * sin(twopi * sinetable/tablelen)
+sinetone = zeros((duration,), dtype = 'float32')
 
-from math import exp, e
-for i in range(len(sinetone)):
-    sinetone[i] *= exp( - e * float(i) / len(sinetone))
-for i in range(attack):
-    sinetone[i] *= exp( e * (float(i) / attack - 1 ) )
+# compute sinetone at floating point period
+for i in range(duration):
+    x = int((i % period) / float(period) * tablelen)
+    sinetone[i] = (sinetable[x] + sinetable[x+1]) / 2
 
-my_sink = sink(sys.argv[1], 44100)
+# apply some envelope
+float_ramp = arange(duration, dtype = 'float32')
+sinetone *= exp( - e * float_ramp / duration / decay)
+sinetone[:attack] *= exp( e * ( float_ramp[:attack] / attack - 1 ) )
 
-i = 0
-while i + blocksize < duration:
-    my_sink(sinetone[i:i+blocksize], blocksize)
-    i += blocksize
+if 0:
+    import matplotlib.pyplot as plt
+    plt.plot(sinetone)
+    plt.show()
+
+my_sink = sink(sys.argv[1], samplerate)
+
+total_frames = 0
+while total_frames + blocksize < duration:
+    my_sink(sinetone[total_frames:total_frames+blocksize], blocksize)
+    total_frames += blocksize
+my_sink(sinetone[total_frames:duration], duration - total_frames)