git.haldean.org
fix sine implementation Will Haldean Brown 6 years ago
2 changed file(s) with 31 addition(s) and 19 deletion(s).
 0 0 import array 1 1 import math 2 2 import struct 3 import symrep 3 import symrep.base 4 4 5 5 def sine(freq): 6 return symrep.Node( 7 "sin", lambda t: math.sin(t * freq(t) / (2 * math.pi)), [freq]) 6 return symrep.base.Node( 7 "sin", lambda t: math.sin(t * freq(t) * 2. * math.pi), [freq]) 8 9 def square(freq): 10 pass 11 12 def _to_short(val, max_amplitude=1.0): 13 short_max = (2 ** 15) - 1 14 val = int(val / max_amplitude * short_max) 15 if val > short_max: 16 return short_max 17 elif val < -short_max: 18 return -short_max 19 return val 8 20 9 21 def to_wav(root, sample_rate, length, stream): 10 num_samples = int(math.ceil(length * sample_rate)) 11 print 'generating', num_samples, 'samples' 12 bits_per_sample = 32 13 14 def sample_t(): 15 i = t = 0 16 while i < num_samples: 17 yield t 18 i += 1 19 t += 1 / sample_rate 20 21 data = array.array("f", (root(t) for t in sample_t())) 22 print 'data is', len(data), 'samples' 23 import pprint; pprint.pprint(data[:20]) 22 bits_per_sample = 16 23 data = array.array("h", map( 24 lambda x: _to_short(x[1]), 25 symrep.base.sample(root, 0., length, 1. / sample_rate))) 24 26 25 27 # begin file header 26 28 stream.write("RIFF") 44 46 45 47 # begin data header 46 48 stream.write("data") 47 stream.write(struct.pack("
 20 20 def __call__(self, t): 21 21 return self.func(t) 22 22 23 def sample(root, min_t, max_t, delta_t): 24 t = min_t 25 while t < max_t: 26 yield t, root(t) 27 t += delta_t 28 23 29 def collect_nodes(root): 24 30 return set([root]).union( 25 31 reduce(set.union, map(collect_nodes, root.deps), set()))