MIDI envelopes
The last tutorial generated notes that turned on and off according to a MIDI controller. Here we will create a more interesting note that has a slow attack and decays after the MIDI note is released, not starts and cuts off abruptly.
We'll also use the note's velocity to determine the note's loudness.
<CsoundSynthesizer>
<CsOptions> -+P -+K ;Same flags as before. If you're not using CsoundAV, ;In Linux you will need to change these flags to: ; -odevaudio -M ;or no flags for MacCsound </CsOptions><CsInstruments>
sr=44100
kr=441
ksmps=100
nchnls=2
;The usual headersmassign 1,2
;Assign MIDI channel 1 to instrument 2instr 2
icps cpsmidi
;As before icps will hold the Herz value of the note playedivel veloc
;The opcode veloc assigns the velocity value of the note to the variable ivel ;Velocity values range from 1 to 128, the standard 7-bit MIDI range
print icps
print ivel
;These past two instructions will display the values of the variables icps and ivel at init time.kenv linsegr 0,0.5,10000* (ivel/128), 3, 0
;This opcode generates an envelope for each note, assigned to variable kenv. ;Notice that for envelopes we tend to use, use k-rate variables ;While audio signals use a-rate variables. This is done to avoid ;unnecessary (and processor costly) precision when calculating ;things like envelopes and control signals. ;the linsegr opcode generates an envelope starting at 0, and rising to an amplitude ;between 0 and 10000 (depending on ivel) in 0.5 seconds (a long attack). ;The note remains held until the MIDI note which triggered it is released, ;when the note will be released for 3 seconds (a long release). ;The final value of the envelope is 0aout oscili 1, icps, 1
;The oscillator oscili is the same as oscil except that it interpolates between points ;in a table. What this means is that the oscillator is smoother. ;Usually interpolation means higher quality, but more processing. ;f-table 1 has changed. See the score section below.
outs aout*kenv , aout*kenv
;Sends the oscillator's signal to the outputs. Notice that this time we don't ;multiply by 10000 but rather use the envelope generator.
endin
;The end of the instrument.</CsInstruments>
<CsScore>
f 1 0 4096 10 1 0.5 0.25 0.125 0.0625
;Generates a curve aproximating a saw wave, from a sum of sinusoids.
f 0 120
</CsScore>
</CsoundSynthesizer>
This tutorial starts to sound more like a real synth. You might want to try different values or GEN functions for f-table 1.