# Faust 101 for the confined

The covid-19 containment gives us at least one excellent opportunity to train! If you've always wanted to get into Faust programming but didn't have the time, here's your chance!

The objective of this workshop is to help you get familiar with the Faust language through very simple examples of signal processing and sound synthesis. The documentation and the examples we will use can be found here:

All examples will be run in the online Faust IDE:

If ever the sounds produced with the IDE are of poor quality, with some clicks, one can use the online editor, which is more rustic, but also lighter:

## Faust in a few words

• Faust is a Domain-Specific Language for real-time signal processing and synthesis (like Csound, Max/MSP, Supercollider, Puredata,. . . ).
• Faust is based on purely functional approach.
• a Faust program denotes a signal processor: a function that maps input signals to output signals.
• Programming in Faust is essentially combining signal processors using an algebra of 5 composition operations: <: :> : , ~.
• Faust is a compiled language, the role of the Faust compiler is to synthesize the most efficient implementations.
• Faust offers end-users a high-level alternative to C/C++ to develop audio applications for a large variety of platforms.

## Part 1: Very simple examples

### Example 1: The simplest Faust program

This is the simplest Faust program imaginable. It contains only one line of code, the definition: process = _;. This program copies the audio input to the audio output.

Let's try this program using the online Faust IDE:


process = _;



Several lessons can be learned from this very simple example:

• a Faust program has at least one definition, that of the keyword process which indicates the entry point of the program.
• a definition always ends with a ;. A common mistake is to forget the semicolon at the end of a definition.
• the _ sign represents one of the primitives of the language (primitives are the predefined functions of the language). It represents an audio cable that lets the signal pass through without transforming it. This is what one calls in mathematics the identity function, the signal that enters on the left comes out on the right identically.

### Example 2: Adding two signals

We saw in the previous example the primitive _. Faust has a large number of primitives, including all mathematical operations.

The + primitive for instance is used to add two signals. It can therefore be used to transform a stereophonic signal (on two channels) into a monophonic signal as in the following example:


process = +;



### Example 3: Multiplying two signals

The * primitive for instance is used to multiply two signals:


process = *;



As you can hear, multiplying the two channels of a signal between them transforms the sound quite drastically.

### Example 4: Parallel composition

Programming in Faust consists in assembling primitive operations to form more or less complex audio circuits. To realize these assemblies, Faust has 5 composition operations: ~, ,, ;, <:, :>.

Let's first look at the parallel composition represented by the comma ,:


process = _, _;



We made a stereo cable and when we play the audio file, we now hear it on both speakers.

It is very important to distinguish between primitives, such as _, + or *, and composition operations such as , or :. Primitives represent operations on audio signals, whereas composition operations are used to link two audio operations together. In other words, you can write + or * alone, because they represent valid audio operations, but you can never write , or : alone because they are used to connect two audio operations. You must always write A,B or A:B.

The primitives of Faust are organized in several categories. We find all the numerical functions of the C language, but applied to audio signals:

Category Primitives
Arithmetic +, -, *, /, ...
Comparison <, ==, !=, <=, ...
Trigonometric sin, cos, ...
Log and Co. log, exp, ...
Min, Max min, max, ...
Selectors select2, select3, ...
Delays and Tables @, rdtable, ...
GUI hslider(), button(), ...

Here is a summary table of the five composition operators:

Syntax Priority Association Description
A ~ B 4 left Recursive Composition
A , B 3 right Parallel Composition
A : B 2 right Sequential Composition
A <: B 1 right Split Composition
A :> B 1 right Merge Composition

### Example 5: Controlling the volume

Let's see an example where we combine three primitives: _, 0.1 and *, with two composition operators: , and :.

The idea here is to lower the volume of the incoming signal to one tenth of its initial value. This is done by multiplying the incoming signal by 0.1:


process = (_, 0.1) : *; // try to replace 0.1 by other values between 0 and 1



Note that we have used parentheses in this example to clearly mark the order in which things should be done. We start by putting _ and 0.1 in parallel, and then compose them in sequence with *.

But, just as in (2*3)+7 were the parentheses are not really necessary because multiplication takes precedence over addition, one could write directly process = _,0.1 : *; without the parentheses, because parallel composing takes precedence over sequential composing. The priority of the composition operators is shown in the previous table.

### Example 6: Controlling the volume with a slider

Instead of controlling the volume by editing the code, it is far more convenient to use a graphical slider. For that purpose we can use a hslider(...), a horizontal slider. It takes five parameters. The first one is the name "volume", then we have the defaut value 0.1, the minimun value 0, the maximum value 1 and a step value 0.1. So here the default value is 0.1:


process = _, hslider("volume", 0.1, 0, 1, 0.01) : *;



### Example 7: Mono Amplifier

We have written very simple programs so far, that fit into one line of code. We will now introduce additional definitions. A definition should be understood as a way of giving a name to something, which saves us from typing the definition every time and makes the program easier to understand:


monoamp = _, hslider("volume", 0.1, 0, 1, 0.01) : *;
process = monoamp;



### Example 8: Stereo Amplifier

Continuing in the same vein, we will define a stereo amplifier as two mono amplifiers in parallel:


monoamp = _, hslider("volume", 0.1, 0, 1, 0.01) : *;
stereoamp = monoamp, monoamp;

process = stereoamp;



Note that even if the hslider volume appears several times in our code, there will only be one in the user interface:

### Example 9: Vertical sliders

Instead of horizontal sliders, we could use vertical sliders. Just replace hslider(...) with vslider(...):


monoamp = _, vslider("volume", 0.1, 0, 1, 0.01) : *;
stereoamp = monoamp, monoamp;

process = stereoamp;



### Example 10: Knobs instead of sliders

By default sliders are ... sliders! You can change their appearance by using the metadata mechanism.

Metadata is information that you put in square brackets in the slider name. For example the metadata "...[style:knob]..." allows you to turn the slider into a rotary knob:


monoamp = _, vslider("volume[style:knob]", 0.1, 0, 1, 0.01) : *;
stereoamp = monoamp, monoamp;

process = stereoamp;



### Example 11: Syntactic sugar

We have used the core syntax of Faust so far. For example to multiply the incoming signal by 0.1, we wrote _,0.1:*. For numerical expressions this notation is not always the most convenient and sometimes we would prefer to use the more traditional infix notation and write instead _*0.1. We can also use the prefixed notation and write *(0.1).

Let's rewrite the definition of the monoamp using the prefix notation:


monoamp = *(vslider("volume[style:knob]", 0.1, 0, 1, 0.01));
stereoamp = monoamp, monoamp;

process = stereoamp;



Here is a table of equivalent notations, with the same expression in all three syntaxes. Keep in mind that infix and prefix expressions are translated to core syntax:

Expression Description
_,0.1:* core syntax
_*0.1 infix notation
*(0.1) prefix notation

These notations can be freely combined. For example, the following expressions are all equivalent:

Expression Description
*(1-m) prefix + infix notation
_*(1-m) only infix notation
_,(1,m:-):* core syntax

### Example 12: A mute button

We would like to be able to mute the sound completely at the touch of a button, without having to change the volume.

Let's add a mute stage to our mono amplifier. In order to mute the signal we just have to mutiply it by 0. We will use for that purpose a checkbox(...), a user interface element that produces a signal which is 0 by default and 1 when it is checked. As we want to multiply the signal by 0 when the checkbox is checked we will use 1-checkbox("mute"):


mute = *(1-checkbox("mute"));
monoamp = *(vslider("volume[style:knob]", 0.1, 0, 1, 0.01)) : mute;
stereoamp = monoamp, monoamp;

process = stereoamp;



### Example 13: Vertical and horizontal Layout

As can be seen in the previous example, by default, the layout of the elements is vertical. You can change this layout by using hgroup(...) and vgroup(...). For example to make the layout horizontal you can write:


mute = *(1-checkbox("mute"));
monoamp = *(vslider("volume[style:knob]", 0.1, 0, 1, 0.01)) : mute;
stereoamp = hgroup("Marshall", monoamp, monoamp);

process = stereoamp;



### Example 14: Differentiate the volume of the two channels

To differentiate the volume control of our two channels, we will parametrize monoamp with a channel number c which will be used to differentiate the name of each volume control. Note that the name c of the parameter must only have one letter to be well interpreted in the slider name "volume %c[style:knob]":


mute = *(1-checkbox("mute"));
monoamp(c) = *(vslider("volume %c[style:knob]", 0.1, 0, 1, 0.01)) : mute;
stereoamp = hgroup("Marshall", monoamp(0), monoamp(1));

process = stereoamp;



### Example 15: Having many channels

We have built a stereo amp, but suppose we wanted to generalize this construction to an arbitrary number of channels. To do so, we will introduce the par(i, N, ...) construction which allows us to put several times an expression in parallel. It is in a way the equivalent of the for() loop of a classical programming language.

In our case we want to indicate the number of channels of our amplifier:


mute = *(1-checkbox("mute"));
monoamp(c) = *(vslider("volume %c[style:knob]", 0.1, 0, 1, 0.01)) : mute;
multiamp(N) = hgroup("Marshall", par(i, N, monoamp(i)));

process = multiamp(2); // try multiamp(4)



## Part 2: Delays and Feedbacks

In this new section we will see two important notions, that of delay with the @ primitive, and that of feedback (from a looped circuit) which will require the use of the recursive composition A~B which allows to loop the outputs of A into the inputs of B, and the outputs of B into the inputs of A.

### Example 1: Monophonic delay of 1 second

Let's start with a very simple example, a monophonic delay of 1 seconds or 44100 samples. We will use the prefix notation:


process = @(44100);

// equivalent to core syntax
// process = _, 44100 : @;



### Example 2: Delay of 0.1 second on the right channel

To hear the delay better, let's put it only on the right channel and leave the left channel unchanged:


process = _, @(4410);



### Example 3: the bouncing of sound on a wall

By combining a delay and an attenuation we can simulate the bouncing of sound on a wall:


bounce = @(4410) : *(0.75);
process = _, bounce;



### Example 4: A simple monophonic echo

To simulate an echo, all we need to do is create a feedback loop. We'll use the recursive composition A~B:


bounce = @(4410) : *(0.75);
monoecho = +~bounce;
process = _, monoecho;



### Example 5: A stereophonic echo

Let's make a stereophonic echo with two monophonic echos in parallel:


bounce = @(44100/4) : *(0.75);
monoecho = +~bounce;
stereoecho = monoecho, monoecho;

process = stereoecho;



We will now generalize our echo with parameters to control its duration and feedback level:


bounce(d,f) = @(d) : *(f);
monoecho(d,f) = +~bounce(d,f);
stereoecho(d,f) = monoecho(d,f), monoecho(d,f);

process = stereoecho(44100/4,0.75);



### Example 7: Slider for the feedback control

We can now add a slider to control the level of feedback:


bounce(d,f) = @(d) : *(f);
monoecho(d,f) = +~bounce(d,f);
stereoecho(d,f) = monoecho(d,f), monoecho(d,f);

process = stereoecho(44100/4, hslider("feedback", 0, 0, 1, 0.01));



### Example 8: Freeze effect

We would now like to prevent the sound level from rising indefinitely when we set the feedback level to 1. The idea is to gradually shut down the input when the feedback level exceeds a certain threshold:


bounce(d,f) = @(d) : *(f);
monoecho(d,f) = *(g) : +~bounce(d,f) with { g = 1 - max(0, f-l)/(1-l); l = 0.95; };
stereoecho(d,f) = monoecho(d,f), monoecho(d,f);

process = stereoecho(44100/4, hslider("feedback", 0, 0, 1, 0.01));



## Part 3: Basic Oscillators

By convention, in Faust, a full-scale audio signal varies between -1 and +1, but we will first start with a sawtooth signal between 0 and 1 which will then be used as a phase generator to produce different waveforms.

### Phase Generator

The first step is to build a phase generator that produces a periodic sawtooth signal between 0 and 1. Here is the signal we want to generate :

### Example 1: Ramp

To do this we will produce an "infinite" ramp, which we will then transform into a periodic signal thanks to a part-decimal operation:

The ramp is produced by the following program:


process = 0.125 : + ~ _;



### Semantics

To understand the above diagram, we will annotate it with its mathematical semantics:

As can be seen in the diagram, the formula for the output signal is: $y(t) = y(t-1) + 0.125$

We can calculate the first values of $y(t)$:

• $y(t<0)=0$.
• $y(0) = y(-1) + 0.125 = 0.125$.
• $y(1) = y(0) + 0.125 = 2*0.125 = 0.250$
• $y(2) = y(1) + 0.125 = 3*0.125 = 0.375$
• ...
• $y(6) = y(5) + 0.125 = 7*0.125 = 0.875$
• $y(7) = y(6) + 0.125 = 8*0.125 = 1,000$
• $y(8) = y(7) + 0.125 = 9*0.125 = 1.125$
• ...

### Example 2: a phase signal

How do I turn the above ramp into a sawtooth signal? By deleting the whole part of the samples in order to keep only the decimal part: $3.14159\rightarrow 0.14159$.

Let's define a function to do this:

decimalpart(x) = x - int(x);


We can now use this function to turn our ramp into a sawtooth. It is then tempting to write:

process = 0.125 : + ~ _ : decimalpart;


From a mathematical point of view, that would be perfectly correct, but we will accumulate rounding errors. To keep total accuracy, it is better to place the operation of the decimal part inside the loop, like this:

process = 0.125 : (+ : decimalpart) ~ _;


We can now try the whole code (think about turning down the volume) :


decimalpart(x) = x-int(x);
phase = 0.125 : (+ : decimalpart) ~ _;
process = phase;



In our definition of phase, the value of the step, here 0.125, controls the frequency of the generated signal. We would like to calculate this step value as a function of the desired frequency. In order to do the conversion, we need to know the sampling frequency. It is available in the standard library as ma.SR and will be setup at start time by the underlying audio layer. To use this standard library we add the following line to the program: import("stdfaust.lib");.

Suppose we want our phase signal to have a frequency of 1 Hz, then the step should be very small 1/ma.SR, so that it takes ma.SR samples (i.e. 1 second) for the phase signal to go from 0 to 1.

If we want a frequency of 440 Hz, we need a 440 times larger step so that the phase signal goes from 0 to 1, 440 times faster:

phase = 440/ma.SR : (+ : decimalpart) ~ _;


This definition can be generalized by replacing 440 with an f parameter:

phase(f) = f/ma.SR : (+ : decimalpart) ~ _;


and changing the desired frequency to phase:

process = phase(440);


### Example 3: Sawtooth signal generator

We can now use the phase generator to produce a sawtooth signal:


import("stdfaust.lib");

decimalpart(x) = x-int(x);
phase(f) = f/ma.SR : (+ : decimalpart) ~ _;

sawtooth(f) = phase(f) * 2 - 1;

process = sawtooth(440);



### Example 4: Square wave generator

We can also use the phase generator to produce a square wave signal:


import("stdfaust.lib");

decimalpart(x) = x-int(x);
phase(f) = f/ma.SR : (+ : decimalpart) ~ _;
squarewave(f) = (phase(f) > 0.5) * 2 - 1;

process = squarewave(440);



### Example 1: sine wave generator

The phase generator is also the basis of the sine wave generator:


import("stdfaust.lib");

decimalpart(x) = x-int(x);
phase(f) = f/ma.SR : (+ : decimalpart) ~ _;
osc(f) = sin(phase(f) * 2 * ma.PI);

process = osc(440);



But now that we have seen how to create a sinusoidal oscillator from scratch, we will use the one defined in the standard Faust libraries:


import("stdfaust.lib");

process = os.osc(440);



### Example 2: a sine wave with volume control

In this second example we used a horizontal slider hslider(...) to control the sound level:


import("stdfaust.lib");

process = os.osc(440) * hslider("gain", 0.1, 0, 1, 0.01);



The first parameter is a string that indicates the name of the slider. It is followed by four numeric parameters. The second parameter 0.1 indicates the default value of the slider, i.e. the value that the slider will deliver when the program is started. Then we have the minimum value 0, the maximum value 1 and the variation step 0.01.

### Example 3: Exercise, add a frequency control

As an exercise, replace, in the previous example, the frequency 440 by a horizontal slider whose name will be freq, the default value 110, the minimum value 40, the maximum value 8000 and the step 1:


import("stdfaust.lib");

process = os.osc(440 /*to replace*/) * hslider("gain", 0.1, 0, 1, 0.01);



### Example 4: Frequency aliasing phenomenon beyond SR/2

A well known problem in the field of digital sound synthesis is frequency aliasing: any frequency beyond half the sampling frequency is folded in the audible spectrum:


import("stdfaust.lib");

// A frequency aliasing phenomenon if one goes beyond SR/2

process = os.osc(hslider("freq", 440, 20, 20000, 1)) * hslider("gain", 0.1, 0, 1, 0.01);



An example of an additive synthesis, where the level of each partial can be set individually:


import("stdfaust.lib");

//----------------------------------------------------------------------
// partial(f,n);
// f = frequency in Hz
// n = partial number starting at 1
partial(n,f) = os.osc(f*n) * hslider("partial %n", 0.25, 0, 1, 0.01);

process = sum(i, 4, partial(i+1, hslider("freq", 440, 20, 8000, 0.001)));



Note the use of the sum(i, n, foo(i)) construction which is equivalent to foo(0)+foo(1)+...+foo(n-1).

### Example 6: Approximation of a square signal by additive synthesis

We saw earlier how to produce a perfect square wave signal. This perfect square signal contains an infinite number of harmonics which, due to sampling, will fold over the audible spectrum, resulting in a less accurate, noisy sound! A square signal can be approximated by additive synthesis, by adding an infinite series of odd harmonics (see https://en.wikipedia.org/wiki/Square_wave):


import("stdfaust.lib");

// Approximation of a square wave using additive synthesis

squarewave(f) = 4/ma.PI*sum(k, 4, os.osc((2*k+1)*f)/(2*k+1));

process = squarewave(55);



As an exercise, change the number of harmonics to see the approximation improve (but do not exceed SR/2).

### Example 7: Approximation of a sawtooth signal by additive synthesis

Similarly, a sawtooth signal can be approximated by additive synthesis, by adding an infinite series of harmonics (see https://en.wikipedia.org/wiki/Sawtooth_wave):


import("stdfaust.lib");

// Approximation of a sawtooth wave using additive synthesis

sawtooth(f) = 2/ma.PI*sum(k, 4, (-1)^k * os.osc((k+1)*f)/(k+1));

process = sawtooth(55);



### Example 8: Band limited oscillators

The problem of aliasing can be solved using band-limited oscillators available in Faust libraries:


import("stdfaust.lib");

decimalpart(x) = x-int(x);
phase(f) = f/ma.SR : (+ : decimalpart) ~ _;
sawtooth(f) = phase(f) * 2 - 1;

//process = sawtooth(440);
process = os.sawN(3,400);



## Part 5: Subtractive synthesis

Subtractive synthesis is the opposite of additive synthesis. It consists in starting from a rich sound, for example white noise, and sculpting its spectrum.

### Example 1: a white noise

A white noise generator:


import("stdfaust.lib");

process = no.noise * hslider("noise", 0.5, 0, 1, 0.01);



### Example 2: lowpass


import("stdfaust.lib");

process = no.noise * hslider("noise", 0.5, 0, 1, 0.01) : fi.lowpass(3, hslider("hifreq", 2000, 20, 20000, 1));



### Example 3: high pass


import("stdfaust.lib");

process = no.noise * hslider("noise", 0.5, 0, 1, 0.01) : fi.highpass(3, hslider("lowfreq", 400, 20, 20000, 1));



### Example 4: bandpass


import("stdfaust.lib");

process = no.noise * hslider("noise", 0.5, 0, 1, 0.01)
: fi.highpass(3, hslider("lowfreq", 400, 20, 20000, 1))
: fi.lowpass(3, hslider("hifreq", 2000, 20, 20000, 1));



### Example 5: resonant


import("stdfaust.lib");

process = no.noise * hslider("noise", 0.5, 0, 1, 0.01)
: fi.resonlp(hslider("hifreq", 400, 20, 20000, 1),
hslider("Q", 1, 1, 100, 0.01),
hslider("gain", 1, 0, 2, 0.01));



### Example 6: fir


import("stdfaust.lib");

// FIR
process = no.noise * hslider("noise", 0.5, 0, 1, 0.01)
<: _, transformation :> _;

transformation = @(1) : *(hslider("gain", 0, -1, 1, 0.1));



### Example 7: iir


import("stdfaust.lib");

// IIR
process = no.noise * hslider("noise", 0.5, 0, 1, 0.01) :
+ ~ transformation;

transformation = @(0) : *(hslider("gain", 0, -0.95, 0.95, 0.01));



### Example 8: comb filter


import("stdfaust.lib");

// IIR, comb filter
process = no.noise * hslider("noise", 0.5, 0, 1, 0.01) :
+ ~ transformation;

transformation = @(hslider("delay", 0, 0, 20, 1)) : *(hslider("gain", 0, -0.98, 0.98, 0.01));



### Example 9: Karplus Strong (1/2)


import("stdfaust.lib");

// Karplus Strong (1/2)
process = no.noise * hslider("noise", 0.5, 0, 1, 0.01) :
+ ~ transformation;

transformation = @(hslider("delay", 0, 0, 200, 1)) : mean : *(hslider("gain", 0, -0.98, 0.98, 0.01));

mean(x) = (x+x')/2;



### Example 10: Karplus Strong (2/2)


import("stdfaust.lib");

// Karplus Strong (2/2)
process = no.noise * hslider("noise", 0.5, 0, 1, 0.01)
: *(envelop)
: + ~ transformation;

transformation = @(hslider("delay", 0, 0, 200, 1)) : mean : *(hslider("gain", 0, -0.999, 0.999, 0.001));

mean(x) = (x+x')/2;

envelop = button("gate") : upfront : en.ar(0.002, 0.01);

upfront(x) = x>x';



### Example 11: Kisana


declare name    "myKisana";
declare author  "Yann Orlarey";

//Modifications GRAME July 2015

/* ========= DESCRIPTION =============

- Kisana : 3-loops string instrument (based on Karplus-Strong)
- Tilt = High frequencies
- Front = High + Medium frequencies
- Bottom = High + Medium + Low frequencies
- Left = Minimum brightness
- Right = Maximum birghtness
- Front = Long notes
- Back = Short notes

*/

import("stdfaust.lib");

KEY = 60;   // basic midi key
NCY = 15;   // note cycle length
CCY = 15;   // control cycle length
BPS = 360;  // general tempo (ba.beat per sec)

process = kisana;

//-------------------------------kisana----------------------------------
// USAGE:  kisana : _,_;
//      3-loops string instrument
//-----------------------------------------------------------------------

kisana = vgroup("MyKisana", harpe(C,11,48), harpe(C,11,60), (harpe(C,11,72) : *(1.5), *(1.5))
:> *(l), *(l))
with {
l = -20 : ba.db2linear;//hslider("[1]Volume",-20, -60, 0, 0.01) : ba.db2linear;
C = hslider("[2]Brightness[acc:0 1 -10 0 10]", 0.2, 0, 1, 0.01) : ba.automat(BPS, CCY, 0.0);
};

//----------------------------------Harpe--------------------------------
// USAGE:  harpe(C,10,60) : _,_;
//      C is the filter coefficient 0..1
//      Build a N (10) strings harpe using a pentatonic scale
//      based on midi key b (60)
//      Each string is triggered by a specific
//      position of the "hand"
//-----------------------------------------------------------------------
harpe(C,N,b) = hand(b) <: par(i, N, position(i+1)
: string(C,Penta(b).degree2Hz(i), att, lvl)
: pan((i+0.5)/N) )
:> _,_
with {
att  = hslider("[3]Resonance[acc:2 1 -10 0 12]", 4, 0.1, 10, 0.01);
hand(48) = vslider("h:[1]Instrument Hands/1 (Note %b)[unit:pk]", 0, 0, N, 1) : int : ba.automat(120, CCY, 0.0);
hand(60) = vslider("h:[1]Instrument Hands/2 (Note %b)[unit:pk]", 2, 0, N, 1) : int : ba.automat(240, CCY, 0.0);
hand(72) = vslider("h:[1]Instrument Hands/3 (Note %b)[unit:pk]", 4, 0, N, 1) : int : ba.automat(480, CCY, 0.0);
//lvl  = vslider("h:loop/level", 0, 0, 6, 1) : int : ba.automat(BPS, CCY, 0.0) : -(6) : ba.db2linear;
lvl = 1;
pan(p) = _ <: *(sqrt(1-p)), *(sqrt(p));
position(a,x) = abs(x - a) < 0.5;
};

//----------------------------------Penta-------------------------------
// Pentatonic scale with degree to midi and degree to Hz conversion
// USAGE: Penta(60).degree2midi(3) ==> 67 midikey
//        Penta(60).degree2Hz(4)   ==> 440 Hz
//-----------------------------------------------------------------------

Penta(key) = environment {

A4Hz = 440;

degree2midi(0) = key+0;
degree2midi(1) = key+2;
degree2midi(2) = key+4;
degree2midi(3) = key+7;
degree2midi(4) = key+9;
degree2midi(d) = degree2midi(d-5)+12;

degree2Hz(d) = A4Hz*semiton(degree2midi(d)-69) with { semiton(n) = 2.0^(n/12.0); };

};

//----------------------------------String-------------------------------
// A karplus-strong string.
//
// USAGE: string(440Hz, 4s, 1.0, button("play"))
// or     button("play") : string(440Hz, 4s, 1.0)
//-----------------------------------------------------------------------

string(coef, freq, t60, level, trig) = no.noise*level
: *(trig : trigger(freq2samples(freq)))
: resonator(freq2samples(freq), att)
with {
resonator(d,a)  = (+ : @(d-1)) ~ (average : *(a));
average(x)      = (x*(1+coef)+x'*(1-coef))/2;
trigger(n)      = upfront : + ~ decay(n) : >(0.0);
upfront(x)      = (x-x') > 0.0;
decay(n,x)      = x - (x>0.0)/n;
freq2samples(f) = 44100.0/f;
att             = pow(0.001,1.0/(freq*t60)); // attenuation coefficient
random          = +(12345)~*(1103515245);
noise           = random/2147483647.0;
};



## Part 6: Synthesis by frequency modulation

### Example 1: frequency modulation


import("stdfaust.lib");

// FM: Frequency modulation

FM(fc,fm,amp) = fm : os.osc : *(amp) : +(1) : *(fc) : os.osc;

process = FM(
hslider("freq carrier", 880, 40, 8000, 1),
hslider("freq modulation", 200, 10, 1000, 1),
hslider("amp modulation", 0, 0, 1, 0.01)
)
<: _,_;



### Example 2: frequency modulation with envelops


import("stdfaust.lib");

// FM: Frequency modulation 2

FM(fc,fm,amp) = fm : os.osc : *(amp) : +(1) : *(fc) : os.osc;

process = FM(
hslider("freq carrier", 880, 40, 8000, 1),
hslider("freq modulation", 200, 10, 1000, 1)*(2+envelop2)/3,
hslider("amp modulation", 0, 0, 1, 0.01)*(0.5+envelop2)/1.5
)
: *(envelop1)
<: dm.freeverb_demo;

envelop1 = button("gate") : upfront : en.ar(0.001, 1);
envelop2 = button("gate") : upfront : en.ar(0.5, 0.5);

upfront(x) = x>x';