Monday, February 25, 2019

ex3. line opcode and Frequency Modulation

The line opcode will interpolate linear values from two endpoints.


We use an lfo's default shape (sine), to modulate the carrier frequency which goes from 220 Hz to 440 Hz during duration of the 40-second sound. It's frequency is modulated by 220 Hz at a rate of 2 Hz.


Now we have added add_instrument method to CSD class. Here we expect a list of strings in opcodes. These are joined to write out the csd for this instrument.


This program generates the frequency modulated program:


# ex3.py
# line opcode and Frequency Modulation

from csd import CSD

csd = CSD(__file__)

csd.s1()

csd.add('giSine ftgen 0, 0, 2^10, 10, 1')

csd.add_instrument(
    num = 1,
    opcodes = ['kfreq line 220, p3, 440',
               'kres lfo 220,2',
               'kenv linen 1, p3/40, p3, p3/40',
               'aOsc poscil 0.5, kfreq+kres, giSine',
               'outs kenv*aOsc, kenv*aOsc' ])

csd.s2()

csd.add('i 1 0 40')

csd.s3()

Now the csd file is:


# csd.py

import os
import time

class CSD:

    def __init__(self, fnam):
        self.lines = []
        self.fnam = fnam.split(os.path.sep)[-1][:-3]

    def add(self, line):
        self.lines.append(line)

    def add_instrument(self, **dic):
        num = dic.get('num', 1)
        self.add('\n\tinstr %d' % num)
        opcodes = dic.get('opcodes',[])
        if len(opcodes)==0:
            print('We need opcodes list')
            return
        string = '\n'.join(opcodes)
        self.add(string)
        self.add('\tendin\n')

    def s1(self, sr=44100, ksmps = 32, nchnls=2, dbfs=1):
        self.add('<CsoundSynthesizer>')
        self.add('<CsOptions>')
        self.add('-o %s.wav -W' % self.fnam)
        self.add('</CsOptions>')
        self.add('<CsInstruments>')
        self.add('sr = %s' % sr)
        self.add('ksmps = %s' % ksmps)
        self.add('nchnls = %s' % nchnls)
        self.add('0dbfs = %s' % dbfs)

    def s2(self):
        self.add('</CsInstruments>')
        self.add('<CsScore>')

    def s3(self):
        self.add('</CsScore>')
        self.add('</CsoundSynthesizer>')
        string = '\n'.join(self.lines)
        fout = open(self.fnam + '.csd', 'w')
        fout.write(string)
        fout.close()
        time.sleep(0.5)
        status = os.system('csound %s.csd' % self.fnam)
        if status!=0: raise Exception ('Could not write wav file')

We have the video here.

No comments:

Post a Comment