# Python Iterator as a Sine Oscillator

I wrote a sine oscillator as a Python iterator class. Not the fastest digital oscillator in the world. Though for now, doing prototype work in pure Python will do just fine, even if it means slow render times. In the long run, Slipmat will require a powerhouse of an engine for real-time audio synthesis and DSP, probably written in C. All in good time.

Here’s the script:

#!/usr/bin/env python
import math
import itertools

class Sine:
'''A sine wave oscillator.'''

sr = 44100
ksmps = 10

def __init__(self, amp=1.0, freq=440, phase=0.0):
self.amp = amp
self.freq = float(freq)
self.phase = phase

def __iter__(self):
self.index = 0
return self

def next(self):
if self.index >= self.ksmps:
raise StopIteration

self.index += 1
v = math.sin(self.phase * 2 * math.pi)
self.phase += self.freq / self.sr
return v * self.amp

if __name__ == "__main__":
a1 = Sine(1, 4410, 0.25)
a2 = Sine(0.5, 8820)
amix = (i + j for i, j in itertools.izip(a1, a2))

for i in amix:
print i

Currently, it produces the same sound as a tree falling in the woods with no one around to hear it; It doesn’t write to a DAC or sound file. At least we can still view the results:

1.0
1.28454525252
0.602909620521
-0.602909620521
-1.28454525252
-1.0
-0.333488736227
-0.0151243682287
0.0151243682287
0.333488736227

Near the bottom of the code is a very simple graph, where two sine wave generators (a1 & a2) are patched into a mixer generator (amix), creating a very rudimentary additive synthesizer. The signals aren’t generated until the for-block at the very end. The script only prints one control-block’s worth of data, 10 samples, which coincides with the value of ksmps found in class Sine. The sample rate and control rate is built right into class Sine, and needs to be moved out.