Monday, August 15, 2016

Minim 4. Create An Instrument

A sine instrument is created which is controlled by a Line UGen which goes from 0.5 to 0 in note's duration.


The class SineInstrument needs out in the noteOn and noteOff methods. Before we can use this class, we have to create the out, the AudioOutput object, which is done in the beginning of setup().


# Ex4.pyde
# Based on Java File in Examples: CreateAnInstrument.pde

'''
This sketch demonstrates how to create synthesized sound
with Minim using an AudioOutput and an Instrument we
define. By using the playNote method you can schedule
notes to played at some point in the future, essentially
allowing to you create musical scores with code. Because
they are constructed with code, they can be either
deterministic or different every time. This sketch
creates a deterministic score, meaning it is the same
every time you run the sketch. For more complex examples
of using playNote check out algorithmicCompExample and
compositionExample in the Synthesis folder. For more
information about Minim and additional features, visit
http://code.compartmental.net/minim/
'''

add_library('minim')

out = None

class SineInstrument(Instrument):
    def __init__(self, frequency):
        # make a sine wave oscillator
        # the amplitude is zero because
        # we are going to patch a Line to it anyway
        self.wave = Oscil(frequency, 0, Waves.SINE)
        self.ampEnv = Line()
        self.ampEnv.patch(self.wave.amplitude)
    def noteOn(self, duration):
        # start the amplitude envelope
        self.ampEnv.activate(duration,0.5,0)
        # attach the oscil to the output so it makes sound
        self.wave.patch(out)
    def noteOff(self):
        # this is called by the sequencer when the
        # instrument should stop making sound
        self.wave.unpatch(out)

def setup():
    size(512, 200)
    global out
    minim = Minim(this)
    # use the getLineOut method of the Minim object to
    # get an AudioOutput object
    out = minim.getLineOut()
    # when providing an Instrument, we always specify
    # start time and duration
    out.playNote(0.0, 0.9, SineInstrument(97.99))
    out.playNote(1.0, 0.9, SineInstrument(123.47))
    # we can use the Frequency class to create
    # frequencies from pitch names
    freq = Frequency.ofPitch("C3").asHz()
    out.playNote(2.0, 2.9, SineInstrument(freq))
    freq = Frequency.ofPitch("E3").asHz()
    out.playNote(3.0, 1.9, SineInstrument(freq))
    freq = Frequency.ofPitch("G3").asHz()
    out.playNote(4.0, 0.9, SineInstrument(freq))
    
    
def draw():
    background(0,0,255)
    stroke(255,0,0)
    # draw the waveforms
    for i in xrange(out.bufferSize()-1):
        line(i, 50 - out.left.get(i)*50,
             i+1, 50 - out.left.get(i+1)*50)
        line(i, 150 - out.right.get(i)*50,
             i+1, 150 - out.right.get(i+1)*50)

This is the output:


No comments:

Post a Comment