Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Hans Gruendel
20.2.2016
1 Content
2 Introduction.......................................................................................................................................4
3 The First Song.....................................................................................................................................5
4 The Graphical User Interface..............................................................................................................6
5 Music Theory very simple...............................................................................................................8
5.1 Pitch............................................................................................................................................8
5.2 Length of the Tone......................................................................................................................9
5.3 MIDI..........................................................................................................................................10
6 The Syntax of Sonic Pi......................................................................................................................11
6.1 Coding Types.............................................................................................................................11
6.1.1 Comments..........................................................................................................................11
6.1.2 Commands.........................................................................................................................13
6.1.3 Parameters.........................................................................................................................14
7 A simple Melody with different Sounds...........................................................................................14
8 The Code Editor...............................................................................................................................18
8.1 Line Numbers............................................................................................................................18
8.2 Navigation.................................................................................................................................19
8.3 Right Mouse Button (MBR).......................................................................................................19
8.4 Copy and Paste..........................................................................................................................21
9 Error Handling..................................................................................................................................22
10 Random Control.............................................................................................................................23
10.1 Random Numbers...................................................................................................................23
10.2 Selection.................................................................................................................................25
10.3 Random Song..........................................................................................................................26
11 Parameter: Synth and Sample........................................................................................................28
11.1 Envelopes................................................................................................................................29
12 Program Structures........................................................................................................................30
12.1 Threads...................................................................................................................................30
12.2 Cue +Sync: Give Inserts...........................................................................................................33
12.3 Loops.......................................................................................................................................34
2 Introduction
Music is one of the truly great achievements of mankind. And there is no man on earth who does not
like music. Software and computers are a recent achievement and many processes and industries are
now reliant. Sonic Pi forms pike between music and software.
Every child can learn the basics of programming with Sonic Pi. It is a lot of fun doing this while
learning a lot about music.
This book describes the fundamentals of Sonic Pi explained in such a way that a child can understand
it. The book is suitable as an accompaniment to teaching as well as for self-learning.
Have fun
The song consists of 3 separate tones. To perform them, you can simply copy the framed lines below
in a window of Sonic Pi and press the <Run> button. Uses for the best the normal copy and paste
functions, or even easier, but somewhat more work: Typing the code in one of the Sonic Pi code
windows.
# The First Song
play :c4
sleep 1
play :e4
sleep 1
play :g4
Code 1. The very first example
And then hear 3 tones in succession. Even if you can easily understand what happens here, I will
explain it briefly, line by line.
Nr.
1-1
Sonic Pi command
# The First Song
1-2
1-3
1-4
play :c4
sleep 1
play :e4
Explanation
Comments are marked with a <#>. Every text right on the
line, Sonic Pi will not play. Thus, the first line is a comment.
Sonic Pi plays the note c4. Do not forget the colon.
For a second, no new note is played.
Sonic Pi plays the note e4.
Sonic Pi works the commands from the top downwards. The comment on the first line is ignored.
What sound on the piano keyboard is
c4?
This is explained in detail in Chapter 5. Here only this: C is the first note of the C major scale. And the
4 represents the 4th octave. e4 is then 2 whole tones higher, and g4 again 2 tones higher. "Sleep 1"
represents a one-second pause.
Every time pushing the <Run> button, you will hear the 3 beeps. Is it possible to change the pitch?
Yes, surely. If I replace the 4 by a 5, the whole little tune starts a full octave higher. If I replace the "c4"
by a "d4", the first done will be heard as a D.
Music Control
Preferences
Y,.
Code Editor
Log Viewer
Workspace Tabs
Help Selection
Help Viewer
Nr.
Sonic Pi GUI
element
2-1
Run
2-2
2-3
Stop
Save
2-4
Rec
Code Editor
6
7
Log Viewer
Help
Help Viewer
Explanation
Music Control
By clicking this button, the code in the current workspace will be playedeven if yet another song in this or any other workspace runs.
All current songs stop with a click.
The code of a song can be stored outside of Sonic Pi. Typically, the code
for each workspace is automatically saved when you close the program
and is the next opening again available. That's why there are basically 2
reasons to save the code externally: I have all existing work spaces
occupied and need an empty one. So I delete the code and have space
for a new song.
Starts recording and the associated generation of a "wav" file. Another
click stops the recording. Recorded is what can be heard between the
two clicks. In case no song is played back, the recording is empty.
Window
Write your song in the code editor. In fact, it is even the only place to
enter something in Sonic Pi.
Shows in chronological order, which has been played.
Here you can search for help. The themes are bundled, and the simpler
things come first.
Shows what is selected in the Help selection.
Table 2. The elements of the Sonic Pi interface.
Topic
Whenever possible use a programming environment for coding, called IDE
(Integrated Development Environment). Two advantages you already know: 1.
different parts of your code are displayed in different colors. 2. And often a tool
that helps you in the completion of commands is integrated. Additional benefits of
an IDE will be described further below.
Comments are important. Each song (each program) should be provided at the
beginning with a comment at least, containing the name etc..
Table 3: Learned for programming - part 1.
5.1 Pitch
The pitch is specified as the first parameter of the "play" method. The "play" method with the
parameter c4 plays a c of the fourth octave, see Figure 3.
The presentation of the notes on the piano keyboard is shown in Figure 4. There are 7 natural tones
(the white keys) and 5 half (the black keys). The C-major scale starts with a C. This is followed by D, E,
F, G, A and B. When starting with the tone A, it is quite easy to memorize the notes: A, B, C, D, E, F, G,
so just the first 7 letters of the alphabet.
C#
Db
D#
Eb
F#
Gb
G#
Ab
A#
Bb
C#
Db
D#
Eb
With the sounds of black buttons is a bit more complicated. Let us look for the tone D for example. It
has a black key to the right and to the left. The black key right from the D plays a semitone higher,
called D-sharp (D# in the figure). The black key left from the D plays a semitone lower, called D-flat
(Db in the figure).
The increase of a half tone is called "sharp" and is abbreviated as "s" in Sonic Pi.
The reduction to a half tone is called "flat" and is abbreviated with "f" in Sonic Pi.
Nr.
Modification
English
Sonic Pi
1
2
Pitch increase
Pitch decrease
sharp
flat
s
f
Sonic Pi
example
cs4
ef5
How is the relation of these parameters to the usual tone lengths like a quarter or a half note? Is
there any provision, how to convert one systems into the other? The answer is unfortunately no, and
the reason for this is that Sonic Pi uses an absolute system, while the conventional music description
operates with a relative system. This means that a quarter note has not always the same length in
seconds. Rather, it is so that the composer sets the speed of the piece or part of a piece, and then
give the note lengths. But even this definition is not absolute and the performer or conductor has a
certain clearance.
But for a specific, single piece of music, an assignment can be made very well. Only the length of the
piece TS and the number of bars NT needs to be known. The ratio of TS/NT gives me then the length
of a whole note in case using a 4/4 bar. To have this length in seconds, even TS must be in seconds or
be converted in advance.
5.3 MIDI
The determination of the pitch we know now. After the command "play" we have to write the note
with a colon including a number for the specific octave, for example "c5". In Sonic Pi there is indeed
another way. We can write instead a single number, as shown in Figure 6.
In fact, "c5" corresponds to the number 72. You will hear exactly the same sound.
You can try it simply by copying Code 2 in the Sonic Pi Code Editor and then run it.
# MIDI
play :c5
sleep 0.5
play 72
Code 2. Midi example.
The same sound would be heard twice. ":c5" and "72" thus mean the same thing. However, there is a
little difference. The normal tone requires a colon after the "play", the MIDI number does not. As a
number of them, incidentally, shown in blue, while the note turns red. Although it is not so important
for the operation of Sonic Pi: MIDI stands for "Musical Instrument Digital Interface" i.e. "digital
interface for musical instruments".
When do I use now which kind of description? Actually, that does not matter. One should use that is
better and easier to handle. If in the normal description I'm home anyway and I know the notes from
school or music lessons, then I use these. If I have, however, a piece of music already present in the
MIDI notation, I stick to it. One thing you should not do, even though it works in Sonic Pi: Mix MIDI
and conventional description in a piece of music.
However, what does not work: Copy a so-called MIDI file into the editor and try to run it. MIDI files
are a proprietary format and are incompatible with Sonic Pi.
Table 5 shows an overview of the assignment. By this we can easily see that MIDI is a simple
numbering of the keys of the piano.
Octave/Tone
A
A
-1
0
1
2
3
4
5
6
7
8
9
9
21
33
45
57
69
81
93
105
117
A#
Ais/
H
B(H)
B(H)
10
22
34
46
58
70
82
94
106
118
11
23
35
47
59
71
83
95
107
119
0
12
24
36
48
60
72
84
96
108
120
C#
Cis/De
s
1
13
25
37
49
61
73
85
97
109
121
D
D
2
14
26
38
50
62
74
86
98
110
122
D#
Dis/Ee
s
3
14
27
39
51
63
75
87
99
111
123
4
16
28
40
52
64
76
88
100
112
124
5
17
29
41
53
65
77
89
101
113
125
F#
Fis/Ge
s
6
18
30
42
54
66
78
90
102
114
126
G#
Gis
7
19
31
43
55
67
79
91
103
115
127
8
20
32
44
56
68
80
92
104
116
128
Comments
Actually not true commands, but indispensable for all coders are the comments. In Sonic Pi they are
marked with a hash at the beginning of the line. Comments are always colored in gray.
Figure 7. The comment in the first line starts with the hash
Comments are a service for others and for the coder. My useful thoughts about a piece can be a
comment. If I want any information to pass on, then I use the comments. At least I can write the song
title, my name and the date of origin as a comment in the first lines. In principle, however, comments
are possible at any point. In the following example there are 3 different types of comments:
1. A comment block with general information in the first lines, which is additionally limited by a start
and finish line, see Figure 7.
2. A single comment line, indicating the beginning of the first voice
3. A comment behind a piece of code describing exactly this.
################################
#
# NGB Example 1 Bach wtc
# Hans Gruendel
# 18.07.2015
#
################################
# Voice 1
idx1 = 0
in_thread do
4.times do
use_synth :fm
play :C4, release: 1, amp:1 + idx1 # That is the first sound
sleep 2
end
Code 3. Comments
6.1.2
Commands
Commands appear in Sonic Pi in black color. In Figure 8, two commands can be seen: "play" and
"sleep".
Commands must be written in Sonic Pi exactly as they are defined. This also applies to the caseinsensitive. Basically lowercase is to use in Sonic Pi. Uppercase or misspelling results in Sonic Pi to an
error message. Fortunately, there is an automatic code completion in Sonic Pi function. Once I
entered the first letter of a command, a small window that contains all the commands that start with
that letter appears. Now there are two ways to proceed. Either I simply type in the next letter, or I am
looking for the command in the list (Figure 9).
6.1.3
Parameters
In Sonic Pi values can be given to commands. This is understandable look at the command "sleep". At
least, you must define how long should the sleep be. Sonic Pi interprets the value in seconds. "Sleep
2" therefore means that here 2 seconds nothing should happen. A fractions of seconds can be
specified as pause lengths, for example, 2.75 means a pause of 2 seconds. The numbers as
parameters are shown in blue.
In addition to the numbers as parameters, there are also strings as parameters possible. As an
example, here are the pitch of the "play" command. "Play: c4" plays the sound c the 4th octave.
These strings that are not numbers, are displayed in red. Figure 10 shows the use of commands.
Figure 10. Parameters are given to the methods "play" and "sleep".
2
3
Topic
Use for programming whenever possible a programming environment called IDE
(Integrated Development Environment). Two advantages you already know:
different parts of your code are displayed in different colors. And often tool that
helps you in the completion of commands is integrated. Additional benefits of an
IDE we discussed later.
Comments are important. Each song (each program) should be provided at the
beginning with a comment at least, containing the name etc.
Parameters for controlling the functionality can be given to many (but not all)
commands.
Table 6: Learned for programming part 2.
################################
#
# Song 2
# Hans Gruendel
# 18.08.2015
#
################################
#Part 1
play :g5, release: 1
sleep 1
play :a5, release: 1
sleep 1
play :g5, release: 0.75
sleep 0.75
play :f5, release: 0.25
sleep 0.25
play :e5, release: 0.5
sleep 0.5
play :f5, release: 0.5
sleep 0.5
#Part 2
play :g5, release: 1
sleep 1
play :a5, release: 1
sleep 1
play :g5, release: 0.75
sleep 0.75
play :f5, release: 0.25
sleep 0.25
play :e5, release: 0.5
sleep 0.5
play :f5, release: 0.5
sleep 0.5
#Part 3
play :g5, release: 1
sleep 1
play :g5, release: 1
sleep 1
play :a5, release: 1
sleep 1
play :b5, release: 0.5
sleep 0.5
play :c6, release: 0.5
sleep 0.5
But at some point even the most beautiful beep has lost its appeal. Time to change the sound. In
Sonic Pi that works with the "use_synth" command. One parameter is the name of the synth. In you
can see how it works.
Need to know what synthesizers are present at all, please visit the tab "synths", see Figure 12.
Incidentally, the set synth is valid until the next use_synth command is executed. If no more synth
commands are in this song, then this synth is used until the end of the song.
And what happens when you would not use any "use_synth" command? Quite simply. Then the
preset synth "beep" will be used.
If you tried some synths then you will certainly have noticed that the first 6 notes are played twice.
How the code looks now, the lines 4-15 and 18-29 are identical. This double of course the effort when
entering the code. It would be nice if you could say Sonic Pi that some lines are to be played 2 or
more times. And indeed there is such a command: "x. times do ... end ". In Figure 13, the usage can
be seen, which makes it possible to output the sound g5 and the one-second pause twice.
################################
#
# Song 2
# Hans Gruendel
# 18.08.2015
#
################################
use_synth :beep
#Part 1&2
2.times do
play :g5, release: 1
sleep 1
play :a5, release: 1
sleep 1
Theme
Code that repeats itself is to avoid. This principle is later addressed several times,
because it is really important. Every programming language has commands that
allow just that.
Indenting is important to improve readability. And Sonic Pi supports us also. Simply
type the ALT and M key together, and already everything is automatically indented
in this window. There are even programming languages that are committed to the
right indentation, otherwise the program is not running.
Table 7: Learned for programming - 2
8.2 Navigation
As in any text editor, there is a cursor that tells you where you can make changes in the code.
In the code window, you can navigate with the arrow keys of your keyboard. Larger jumps can
performed with the screen up and As in any text editor, there is a cursor of tells you where you can
just make changes in the code
In the code window, you can navigate with the arrow keys of your keyboard. Larger jumps you can
perform with the page up and page down keys, or using the mouse and scroll bars (see Figure 14).
Nr.
Command
Undo
Keyboard
Shortcuts
Alt +Z
Redo
Meaning
Application
Alt +<Shift>+ Z
Cut
Alt + X
Copy
Alt + C
Paste
Alt +V
Delete
Select All
Alt + A
The so called, context menu opens when you push the right mouse button. The commands in this
menu are customized to the situation. Which is good, because you have a good overview of
commands available and usable in this moment.
Something to copy and paste to another location works in many programs. This can be an image or a
text or a table. And it also works with the code in the editor. Just marking the according code with the
keyboard, and then cut / copy and paste them at other locations.
As explained above, Sonic Pi supports the whole thing with keyboard shortcuts. Perhaps you've
noticed that the "Alt" key is used in Sonic Pi. And maybe you're used to it from many other programs
to use the "Ctrl" key. The Ctrl key works in Sonic Pi actually.
And it gets even better. You can also insert the code in other programs, for example, a different editor
or in an email. Because code are always ordinary characters, so letters and numbers. This works with
the code of other programming languages, too. That is useful for many activities:
1. You've written something in the code editor and want it to move to another location, because you
want to change the order of your code.
2. You want to save your code outside of Sonic Pi. Thus you can copy it into another program.
3. You want to send to someone your code as email. Thus you can just copy it in an open e-mail.
9 Error Handling
Programming languages are very accurate. The use and the spelling of all instructions must be strictly
adhered to. This is also in Sonic Pi.
Sonic Pi checked only during playback of the song if it contains errors. If this is the case, then stops
Sonic Pi at the first occurring error and displays an error message. The error message includes an
indication of the number of work space and the line. Then there is a short concise description of the
fault. And even better: Sonic pi identifies the row at the line beginning with a small arrow. Figure 16
shows an example.
The method
scale
expected in the following brackets 2 arguments, namely first the key and then the type of scale. The
possible types are predefined in Sonic Pi. "de" is not a type, and accordingly the error message
occurs:
Runtime Error: [workspace 0, line 10] Unknown scale name: de
What error message is given, if only one argument is passed? That's easy:
Runtime Error: [workspace 0, line 10] Wrong number of arguments (1 for 2)
Explanation: (1 for 2), means that 2 arguments are expected, but only 1 given
10 Random Control
Random plays an important role in many events. But what is random exactly?
Probably you know some systems that work randomly. A well-known is the drawing of the lottery
numbers or the throwing of a dice playing a game. The coincidence of events is due to the
impossibility of predictability of events and the concept of randomness is closely linked to the theory
of probability.
When you run this example, the note 60.9763 is displayed in the Log Viewer. Although it is well
known that no MIDI note with exactly this value exists. There are indeed only integer values. Sonic Pi
then rounded up from 60.9763 to simply a 61.
But that's not the only thing to wonder. Even more amazing is that the randomly generated number is
known in advance. What's that for a coincidence?
In fact, that's not a real coincidence. Furthermore, Sonic Pi play every time the same note, if we press
"Run". This behavior is quite typical for programming languages. The numbers created depends on a
start value. To change the value, we have to set this start value by using the
use_random_seed n
method, wherein n is an arbitrary natural number.
################################
# Random control 2
# Hans Gruendel
# 18.08.2015
#
################################
use_random_seed 20
play rrand(50, 70)
Code 7. Method rrand for generating random numbers with seed in advance.
Every time I now change the value of n, then the tone changes. Incidentally, the tone remains
between 50 and 70, because these 2 numbers are given when the method when calling. They are the
lower and upper limit. Table 9 lists the random methods on Sonic Pi.
1
Nr.
Method
use_random_seed n
rrand(r1, r2)
rand r2
rrand_i(n1, n2)
rand_i(n1, n2)
Meaning
Initializes the random
number generator. From
initialization depends the
value that is generated by
the following random
methods.
Produces randomly a value
between R1 and R2,
exclusive those two limits.
In the example to the right,
0.2 or 0.5 is never returned
Creates a random number
between 0 and R2, or if no
parameter is used only
between 0 and 1
Works like rrand, however,
the random number is
always an integer
Works like rand, however,
the random number is
always an integer
Example
use_random_seed 5
sleep rand
10.2 Selection
The completely free generation of random numbers is one thing. Slightly restrictive operates the
<choose> method. <choose> randomly chooses from a list of a value. The code for this is shown in
Code 8
################################
# Zufallssteuerung 2
# Hans Gruendel
# 18.08.2015
#
################################
play choose([60, 61, 62])
Code 8. Method choose for the random selection
Using the already known <times> method the behavior of <choose> can be better understood. In the
log viewer output is shown. <choose> first selects the value 60, then follow 61, 60, 61, 61, 62, 60, 62,
60, 60.
Figure 17. The choose method selects from the values 60, 61, and 61
################################
# Random
# Hans Gruendel
# 18.09.2015
#
################################
define :my_loop do
use_synth :tb303
sample :drum_bass_hard, rate: rrand(1, 2)
sleep 0.25
sample :drum_bass_hard, rate: rrand(1, 3)
sample :drum_cymbal_closed, rate: rrand(0.5, 1)
sleep 0.2
sample :drum_cymbal_closed, rate: rrand(1, 2)
sleep 0.3
sample :drum_cymbal_closed, rate: rrand(2, 3)
play choose(chord(:c2, :major)), release: 1.75, cutoff: rrand(60, 110),amp:0.2
sleep 0.25
end
define :choir do
2.times do |idx1|
pan_around= -1 + idx1*0.1
sample :ambi_choir, rate: 1.1, amp: 0.4, pan: pan_around
sleep 0.25
idx1 += 0.1
end
4.times do |idx1|
pan_around= -1 + idx1*0.1
sample :ambi_choir, rate: rrand(1, 1.2), amp: 1.5, pan: pan_around
sleep 0.5
idx1 += 0.1
end
end
in_thread(name: :looper1) do
loop do
harmonics(6, [:f2, :f3, :f1, :e2, :e4, :e3])
end
end
in_thread(name: :looper) do
loop do
my_loop
end
end
in_thread(name: :looper2) do
loop do
choir
end
end
define :sound1 do |num|
use_synth :fm
play num
use_synth :pretty_bell
play num
use_synth :sine
play num
use_synth :tri
play num
end
in_thread(name: :looper1) do
loop do
sound1(:c2)
sleep 1
sound1(:g2)
sleep 1
sound1(:f2)
sleep 1
sound1(:c2)
sleep 1
end
end
Code 9. Random song
If you want to find out where random methods are used in this song, then search for the string
"rand".
################################
# Parameter
# Hans Gruendel
# 18.08.2015
#
################################
use_synth:dark_ambience
play:g1, amp:6, release:2
Code 10. Parameter of the <play> method
In the code, a colon after the word "play" is followed immediately from the tone, here g1. This is
followed by further parameters, which are separated by a comma. The parameter <amp> is set to the
value of 6, the parameter <release> is set to the value of 2.
The method <play> expect first of all the value of the pitch. Then the following parameters are not
tied to a particular order. Sonic Pi detects the parameters by the identifier which is put in front of the
colon.
A typo in the parameter identifiers(e.g. play: g3, amp: 6, relaese: 2) creates no error message in Sonic
Pi. Rather, this parameter is ignored. Not ignored however is the absence of a comma or colon. There
is indeed an error message given. More about the error messages from Sonic Pi in Chapter 9.
Which parameters are now available for each method. The parameters commonly used can be
learned by heart very quickly. Basically, there is a documentation of all parameters. For <play>, the
parameter descriptions can be found in the help in <synths> for each available synthesizers, see .
Figure 18. The parameter of the <play> method and there meaning
11.1 Envelopes
The time sequence of the volume of a sound is described by its envelope. This is not only for Sonic Pi
the case, but also for other electronic tone generators. Also every natural instrument has (at least)
one envelope. An instrument or a sound can be long or short, it can immediately be noisy or slowly
aloud, it can swing or sudden end. And in Sonic Pi, some of the parameters of the <play> are used to
produce an envelope. shows a graphical representation of this.
The sound is divided into 4 sections. <attack> specifies how long the sound gets louder and reaches
the <Attack Level>. Then the sound volume decreases as long as the <decay> parameter specifies.
This is followed by <sustain> and <release>. All time parameters are specified in seconds. The sum of
all time parameter specifies the length of the sound.
12 Program Structures
12.1 Threads
Threads are available in many other languages. They are used to process multiple tasks in parallel. In
Sonic Pi they serve to encode several instruments separately. An example for this is shown in Code
11. You just have to tell Sonic Pi where the parallel portion begins (in_thread do) and where it ends
(end). Everything in between is paralleled. Both commands are shown in bold in the example.
###############################
# threads
# Hans Gruendel
# 20.08.2015
#
################################
in_thread do
sleep 17
15.times do
sample :bd_zome
sleep 2
end
end
in_thread do
sleep 16
4.times do
use_synth :fm
play :a3, attack: 0.01, release: 1
sleep 0.5
play :a4, attack: 0.01,release: 1
sleep 0.5
play :c5, attack: 0.01,release: 1
sleep 0.5
play :e5, attack: 0.01,release: 1
sleep 0.5
play :g3, attack: 0.01, release: 1
sleep 0.5
play :g4, attack: 0.01, release: 1
sleep 0.5
play :b4, attack: 0.01, release: 1
sleep 0.5
play :d5, attack: 0.01, release: 1
sleep 0.5
play :e3, attack: 0.01, release: 1
sleep 0.5
play :g4, attack: 0.01, release: 1
sleep 0.5
play :a4, attack: 0.01, release: 1
sleep 0.5
play :e5, attack: 0.01, release: 1
sleep 0.5
play :f3, attack: 0.01, release: 1
sleep 0.5
play :f4, attack: 0.01, release: 1
sleep 0.5
play :a4, attack: 0.01, release: 1
sleep 0.5
play :c5, attack: 0.01, release: 1
sleep 0.5
end
end
in_thread do
5.times do |idx3|
with_fx :reverb do
use_synth :fm
play :a3, attack: 0.01, release: 2, amp:1- 0.2*idx3
play :a4, attack: 0.01,release: 2, amp:1 - 0.2*idx3
play :c5, attack: 0.01,release: 2, amp:1 - 0.2*idx3
play :e5, attack: 0.01,release: 2, amp:1 - 0.2*idx3
sleep 2
play :g3, release: 2, amp:1 - 0.2*idx3
play :g4, release: 2, amp:1 - 0.2*idx3
play :b4, release: 2, amp:1 - 0.2*idx3
play :d5, release: 2, amp:1 - 0.2*idx3
sleep 2
play :e3, release: 2, amp:1 - 0.2*idx3
play :g4, release: 2, amp:1 - 0.2*idx3
play :a4, release: 2, amp:1 - 0.2*idx3
play :e5, release: 2, amp:1 - 0.2*idx3
sleep 1.25
play :f3, release: 2, amp:1 - 0.2*idx3
play :f4, release: 2, amp:1 - 0.2*idx3
play :a4, release: 2, amp:1 - 0.2*idx3
play :c5, release: 2, amp:1 - 0.2*idx3
sleep 2.75
end
end
end
in_thread do
sleep 9
5.times do
sample :drum_bass_hard, rate:0.5, amp: 1.3
sleep 2
sample :drum_bass_hard, rate:0.5, amp: 1.3
sleep 2
sample :drum_bass_hard, rate:0.5, amp: 1.3
sleep 1.25
sample :drum_bass_hard, rate:0.5, amp: 1.3
sleep 2.75
end
end
Code 11.in_threads command code
Of course, the question arises whether parallel threads are always necessary, or when they actually
make sense. First of all, they are not necessary at all. Several instruments can be coded without
threads. If tones are to be played at the same time, then one <play> method could follow another
directly. The <sleep> instructions you have to calculate accordingly. The advantage is that the
temporal sequence of sounds can be seen directly in your code. The downside is the difficulty to
evaluate the <sleep> times and the increasing complexity which makes it difficult to maintain the
code.
Code 12 uses this example again. In that, you can recognize how Cue and Sync works. At the
beginning, please put the comment sign before it:
#cue: tick_drum
#SYNC: tick_drum
Well, drum_heavy_kick would be played twice, at 0.6 seconds and 1.6 seconds. Nothing else would
be expected using waiting periods of 0.6 seconds (sleep 0.6) and of 1 second (sleep 1). Without
uncomment drum_heavy_kick is played at 3 seconds and 6 seconds exactly when the Cue call is
executed.
Now, what happens when the Cue or the Sync call missing?
a) Cue missing: It will not be executed, what stands behind the associated Sync call.
b) Sync is missing: Cue is ignored and the code in the 2nd thread runs immediately.
Incidentally, the Sync command must be run always first. Would this be executed after the Cue call,
then the Cue will be ignored.
################################
# Cue and Sync 2
# Hans Gruendel
# 20.09.2015
#
################################
in_thread do
2.times do
sample :guit_e_slide
sleep 3
cue :tick_drum
end
end
in_thread do
sleep 0.6
sync :tick_drum
2. times do
sample :drum_heavy_kick
sleep 1
end
end
Code 12. Cue and Sync example
12.3 Loops
Music is repetition. There are almost no pieces of music in which note sequences are not repeated.
Completely obviously happens this in the percussion tracks of pop music. They are even so dominant
that 30 or more years ago, the first drum machines have been used in which the sequence of sounds
was really quite rigid.
Code 13 is a loop sample. The command that starts the loop is <x.times do>, where x is the number of
iterations. Also 0 is possible, then the loop is not executed. Decimals are also eccepted in for x in
Sonic Pi. The value is simply rounded. So 4.5 means 4 iterations.
All commands up to the next <end> are looped.
################################
# Loops
# Hans Gruendel
# 20.08.2015
#
################################
in_thread do
sleep 17
15.times do
sample :bd_zome
sleep 2
end
end
Code 13. Loops
################################
# With / Echo
# Hans Gruendel
# 20.08.2015
#
################################
sample :ambi_piano
sleep 2
in_thread do
with_fx :echo do
sample :ambi_piano
sleep 6
end
end
Code 14. With_fx used for the echo effect
What effects are there? In Sonic Pi the effects are explained in the "Fx" tab of help, as shown in Figure
21. Each effect can be modified using parameters.
A complete description of the effect (and also any other effect) can be found in the help, as shown in
Figure 22. The description is structured like the following:
1. All parameters of the effect are mentioned
2. A small example with no parameters is given
3. A brief description of the effect: what it does
4. The number, in which the effect was introduced
5. A detailed description of all parameters with the range in which the parameters can be varied and
the default value. This is the value that uses the effect, if the parameter is not specified by us when
we call it.
3 important effects will be explained here with their parameters.
12.4.1 Distortion
"Distortion" is a typical guitar effects. The sound is somehow unclean and dirty what makes it more
interesting than a clean sound. In the Code Editor that would look like this:
with_fx: Distortion do
Play: g4
end
pre_amp
Before my sound goes into the amplifier's (now figuratively speaking) I can adjust the volume. 0
means silent, 1 is loud. Default value is 1.
distort
That is the strength or the level of distortion. 0 here means little, 1 means a lot. The default value is
0.5.
12.4.2 Echo
The echo effect in Sonic Pi does exactly what one would expect: a sound is repeated (once or several
times) quieter in a certain time interval.
use_synth: FM
with_fx (echo, delay: 0.25, decay: 8) do
Play 55
end
Now to the possible parameters of echo:
amp
We know this parameter already from the effect "Distortion" Here again "amp" is the abbreviation for
"amplifier" and referred to the gain of sound. Values between 0 and 1 are possible.
mix
See the description of the effect "Distortion".
pre_amp
See the description of the effect "Distortion".
phase
Specifies the time interval in seconds between the tones of individual echo. The default value is 0.25.
decay
Indicates the number of repetitions.
max_phase
Specifies the maximum possible period of echoes in seconds. The default value is. 2.
12.4.3 Reverb
Reverb is an effect in which the tone sounds as if it is played in a large room or a den. In pop music,
reverb is the standard effect on the vocals and correspondingly widespread.
with_fx: Reverb do
Play: c4
end
amp
See the description of the effect "Distortion".
mix
See the description of the effect "Distortion". Default is 0.4.
pre_amp
See the description of the effect "Distortion". Default 1.
room
The strength of the room: 0 means no space and therefore no reverb, 1 means a strong reverb. The
default value is 0.6.
damp
High frequencies (i.e. the high proportion in the sound) are muted. 0 denoting no damping, and 1
maximum attenuation. The default value is 0.5.
All effects work in Sonic Pi in the same manner. Always the sounds to be played with an effect, starts
with
with_fx
and ends with
end
It is not necessarily worth to memorize all the parameters of all effects. Conveniently, the values that
can take parameters, are set quite logical. 0 means nothing or minimum, 1 is the maximum, values
between 0 and 1 have an increase in effect.
13.1 Variables
The following example should show what a variable is and how it works.
Imagine you want to produce a series of tones, and from note to note the tone should be higher. Of
course it is possible to encode the appropriate number of <play> instructions and to adjust each tone.
But it's also a lot of work. For a simpler solution please take a look at Code 15. The crucial points have
been marked bold. First, there is a kind of equation, which in reality is an assignment:
tone = 60
So 2 are things done. First, the variable is created with the name "tone". Secondly, a value of 60 is
assigned to it. Two lines below the variable (MIDI pitch is 60) is played:
play sound
And then the variable is incremented by the value 1.
tone = tone + 1
################################
# Variables
# Hans Gruendel
# 25.08.2015
#
################################
in_thread do
use_synth :fm
play :g4
sleep 2
tone = 60
10.times do
play tone
sleep 1
tone = tone + 1
end
end
Code 15. Variables
Because the code contains a loop 10 tones are played.Figure 23 shows the code editor and the log
window. When running the code the value of the variable increases. With each playing the tone pitch
increases by 1.
A word about the assignment. From the Math classes your knows the usage of the equal sign, and
also variables and equations. The equal sign means in all of mathematics, that the left and right of
the equal sign is the same value or the same term. This is different in software programming.
tone = tone + 1 is not right for any value that is used in tone, definitely. If, for example tone has a
value of 60, then there would be 60 = 61 and that would be wrong. We must not forget that the equal
sign in software programming stands for an assignment. Here, the term right of the equal sign is
evaluated (tone + 1) and assigned to the variable on the left of the equal sign.
It should be noted that each variable is assigned to a number at the time of code execution. If this is
not the case, then it comes to a termination of the program (see Figure 24) with the output of the
following error message:
<undefined local variable or method `kneu '>
The error message appears in English, which is also the case in many other programming languages.
But it is relatively easy to understand what in other languages would not always be the case: The local
variable or method "kneu" is not defined. So it is not known and it was not a numerical value
assigned.
More about error messages in Chapter 9.
Figure 24. Unknown variable and error message while program execution
There is a second, better way to incorporate a counter in a loop: using the loop command <x times
do> with the counter as a parameter. For this it must be enclosed in vertical bars: | loopcounter |. Of
course you can use any meaningful name. And you should avoid names that have already been
allocated by Sonic Pi such as "use_synth".
In the increased variable is visible. The log view shows a value of 60 for the first sound in the loop.
Thus "loopcounter" has the value zero in the first go. In each further iterations the value is increased
by 1. The pitch will change accordingly.
The use of a variable in loops is only one reason to work with variables. There are two important
more:
1. Designation of numbers
Numbers in the Code are fairly normal. In Sonic Pi numbers are used for many parameters. At first
glance, these numbers are also plausible. Later, or for other people, they are not so transparent. That
is why one of the basic principles, not to use numbers (magic numbers) as a parameter, but assign
self-explanatory variables and then use these. It is possible to use the variable in many places. If the
value should be changed, it needs to be done just at only one location in the code, namely, where the
allocation takes place.
2. Storage of return values
Methods can give back a return value after finishing. That could be a result of a calculation or a value
describing the success state of the method run. These return values can be assigned to variables and
later be used.
13.2 Controls
If you have played a sound once and will repeat this changed slightly, then Controls offer the relevant
functionality. For this the play command is assigned to a variable and this variable can later be
modified with the control-command and the appropriate parameters. It would look like this:
s = play 70, release: 6
sleep 1
control s, note: 65
Here, the pitch is changed from 70 to 65. A simple example to Controls are shown in Figure 26.
Controls to change parameters.
The change happened suddenly here. But Sonic Pi also allows a sliding change. This can be done by
using the slide parameter. If you want to change the pitch for example, this might be done as follows:
myControl = play 60, release: 5, note_slide: 1
sleep 0.5
control myControl, note: 55
This example clearly shows the coding of the addition of two numbers. However, one can wonder
what advantage it offers. It would be easier to write
Sleep 3
sleep 3
Correct it only makes sense if you use variables, as can be seen in Code 16. The "ring_c_d" function is
called twice. Once with the value "i" and then with "i + 1". "i" is incremented with each pass of the
loop.
16.times do |i|
ring_c_d i
sleep 0.25
ring_c_d i+2
sleep 0.25
end
The resulting number is different for each loop. That's why you can not enter the same number as a
result of the addition.
################################
# With / Echo
# Hans Gruendel
# 20.08.2015
#
################################
# Operators
# Hans Gruendel
# 25.08.2015
#
################################
in_thread do
16.times do |i|
ring_c_d i
sleep 0.25
ring_c_d i+2
sleep 0.25
end
end
define :ring_c_d do |tone|
all_tones = [:c3, :e3, :g3, :c4, :d3, :f3, :a3, :d4].ring
use_synth :fm
play play all_tones[tone]
end
Code 16. Addition of a number and a variable
14 Data Structures
Variables we have already met. In Sonic Pi it is possible to combine multiple values or variables in a
structure. Later in the code, these structures can be used and modified.
element is as always addressed by the index 0. But also 4, 8, 12, etc would work. The second element
can then be addressed by the index 1 and 5 and 9, etc..
Now you have to know how to create a ring. There are 2 ways, but I want to present here only one.
Just append to the list a point and afterward the word <ring>, as shown in the following example.
[40, 60, 69, 55].ring
The notation is (almost) consistent with many other programming languages, where you can modify
objects using methods. That list [..] is here the object, and the method <ring> generates the ring and
the point is set in between to let Sonic Pi know that two things exists here.
14.2 Chords
Chords are collections of tones like lists are sometimes. Chords have the advantage that they are
already defined and usable immediately. In the example in Figure 28 a C major and in C-minor triads
are played. In general the arguments of the chord method are the basis tone first and second the
type of the chord.
It is visible in the log viewer that the chords are quite similar. Actually, only the tone in the middle is
different. Besides the major and minor chords, Sonic Pi knows a lot of other chords, sometimes also
less known as the augmented or diminished seventh chord etc
Doing experiments with chords is fun. And the best is that you need not to know them all by heard. In
the code editor Sonic Pi shows to you all types of chords available. Just press the comma key after
you wrote the basic tone, see Figure 29.
Figure 29. All available chords in Sonic Pi are visible after pressing the comma key.
With the method play chord () all the notes of a chord are played simultaneously. Need to play all
sounds in succession, then you should use "play_pattern" instead of "play".
play_pattern chord(:c4, :dim7)
The pauses between the notes are exactly one second. And if you want to use a different break time,
then one give it as in extra parameter:
play_pattern_timed chord(:E3, :m7), 0.25
14.1 Scales
A scale is a sequence of ascending tones. Figure 30 shows a code example, which plays the C-major
scale. This scale contains 8 tones, and begins as the name suggests, with a tone C. This is followed by
6 more tones and then there is a C again, now an octave higher. From the first to the second C the
frequency of the sound doubles. This is a characteristic feature of each scale.
The easiest way to play a musical scale is to use the play command. After the play follows the
command "scale" with 2 arguments in parentheses: First, the root of the scale, followed by the type
of scale. Below it is an example for a major scale:
play scale(:c4, :major)
Behind the right bracket other parameters can follow for the play command. Since "c4" represents a
note, I can also use the appropriate MIDI numerical value, for example, if I write a counter in a loop.
This is done in Code 17.
################################
# Scales
# Hans Gruendel
# 18.09.2015
#
################################
use_synth :fm
4.times do |ix|
play_pattern_timed scale(ix+50, :major), 0.25
sleep 1
end
Code 17. Scales
What you now have to know about scales? In Europe heptatonic scales are widespread, which
consists of 7 different tones as the name suggests. What types of scales are available in Sonic Pi?
Here 2 examples:
major: These scales consist of the following steps: full tone - full tone semi tone - full tone - full tone
- full tone semi tone
minor: These scales consist of the following steps: full tone - semitone - full tone - full tone - semitone
- full tone - full tone
Sonic Pi could show all available scale types -see Figure 31.
15 Functions
Functions are components in the code that do something specific. You can define the function once
and then call it any number of times. So you can save quite a bit of code and will avoid repetition in
the code. As an example can be seen in the function "sound1" in the code editor, see Figure 32.
Each function begins with the keyword <define> and ends with <end>. All lines between them belong
to the function.
In the example "sound1" a distinctive sound, which consists of 4 basic sounds for the corresponding
Synths are set in the function. The pitch for all sounds is the same, because every play statement uses
the argument num. You simply can copy Code 18 and try it.
###############################
# Functions
# Hans Gruendel
# 25.08.2015
#
################################
in_thread do
sound1 64
sleep 2
sound1 61
end
define :sound1 do |num|
use_synth :fm
play num
use_synth :pretty_bell
play num
use_synth :sine
play num
use_synth :tri
play num
end
Code 18. Example of a function
In this example, the function is called twice. Once using the parameters 64, and then with the
parameters 61. When playing you can hear 2 sounds with different pitches.
With this function, a parameter is just passed, namely a number that is assigned when you call the
variable "num". In the function definition, the variable is included in a vertical bar "|".
The transfer of only one variable is already quite practical. But how does the use of features in case
you want to additionally adjust tone length. So then you need 2 variables. Code 19 is exactly this
example.
The parameters are always separated by a comma. This applies both to the function call, and for the
definition of the function where the two parameter names are then enclosed by the vertical bars. The
assignment of the values in the calling function to the variables in the definition is done through the
order: The first value is assigned to the first parameter, the second value to the second parameter,
and so on.
################################
# Variables -2
# Hans Gruendel
# 25.08.2015
#
################################
in_thread do
sound1 64, 1
sleep 2
sound1 61, 3
sleep 2
end
define :sound1 do |num, length|
use_synth :fm
play num, release: length
use_synth :pretty_bell
play num, release: length
use_synth :sine
play num, release: length
use_synth :tri
play num, release: length
end
Code 19. Function with 2 variables
What happens if the number of parameters of the call and the function definition does not match?
Well, then there is an error message which is shown in Figure 33. More on this in Chapter 9.
Figure 33. The function sound1 is called in line 9 with to few parameters
Let's look at the example carefully and consider what can be improved. I can think of 3 things
spontaneously:
1. Name of function: sound1 says already what this is about, namely a sound, but the "1" is still very
unspecific. Sound_fm & 3 would clearly be better here.
2. No explanation of what the function does: still missing the comment.
3. In Sonic Pi and in many other languages arguments can be predefined with a fixed value. Code 20
indicates how this works. The second argument of the value 0.1 is assigned. There are now 2 ways.
Either I call the function with 2 arguments, then these 2 are used, or I'll call with 1 argument, and
then the value of 0.1 is automatically used for the second argument.
use_synth :sine
play num, release: length
use_synth :tri
play num, release: length
end
Code 20. Default of arguments
Another example is shown in Code 21. The loop parameter i is passed to the
function ring_c_d when calling it. It is irrelevant that the parameter in the
function definition has a different name: tone. Since the loop is done 16 times,
the function is called 16 times and 16 sounds are played. As the ring structure
contains 8 tones, it is walked through completely 2 times.
################################
# functions and rings -3
# Hans Gruendel
# 25.08.2015
#
################################
in_thread do
16.times do |i|
ring_c_d i
sleep 0.25
ring_c_d i+2
sleep 0.25
end
end
define :ring_c_d do |tone|
all_tones = [:c4, :e4, :g4, :c5, :d4, :f4, :a4, :d5].ring
use_synth :fm
play play all_tones[tone]
end
Code 21. Function and ring structure
Topic
Functions are an important part of programming. The principle is: defined once and
called at several locations in the program. And just as important: A function should
always provide a logically limited functionality. No more and no less. If a function
only has a command, then that is not enough. One would rather than calling the
function use the command directly. On the other hand is a function that includes
100 or more commands, too big and certainly not only responsible for one thing.
Variables are important. They should always be used instead of numbers. And they
should have a meaningful (i.e. self-explanatory), name. There are 2 places to
introduce variables: First at the beginning of a program or function and second
when they are needed. And I think the second option is the better one and I would
also recommend it. Option 1 makes only sense if one provides a whole bunch of
variables that are initialized with values.
Table 10: Learned for programming.
Code
Code is executable text. This means there is a program that uses the code and therefore does
something. In Sonic Pi music is made, in other programs calculations are performed or data are
stored suitable.
Comments
Comments explain the code and will not be executed. Each comment begins in Sonic Pi with a #.
Default
In many software programs defaults are used. They are usually used when the associated control
parameters are not specified.
Editor
In general, an editor is a tool to write in text and in the world of programming an editor is used to
enter the code. In Sonic Pi is the editor part of a program. The editor often provides additional
features such as a color coding. That means, various components of the code are displayed in
different colors. Another important feature is the automatic code supplement. All this provides Sonic
Pi.
Error
see error messages
Error Messages
Code may contain errors. If the code is executed, it must be exactly consistent. If not the program
prints an error message. Sonic Pi also outputs the line number, so that the error can be found easily.
Functions
Functions are parts of the code dedicated to a certain purpose. The code is defined once in a function
and can be called as often as wanted.
Methods
Methods and functions are pretty much the same. A collection of commands, together serve a
purpose.
MIDI
Abbreviation for "Musical Instrument Digital Interface", which is a definition of a music notation.
Parameter
see arguments
Programming Language
Includes the commands to execute. Programming languages are always unique.
Variable
A variable is a container which can store a single value or even multiple values which can be modified
from the code.
Frequency
Number of repetitive events in one second.
Key
The smallest unit of a musical piece.
Pause
No sounds are played. The command is "sleep".
Sample
A fairly short passage of a piece of music or a sound that was recorded and then used in another
song.
Scale
The ascending sequence of tones that have a certain distance from each other.
Time
The pooling of individual notes in a group. Is the same length for a particular piece of music, for
example, a three-quarter (3/4) time.
Figures
Figure 1. The Graphical User Interface of Sonic Pi with a simple example..............................................5
Figure 2: GUI elements of Sonic Pi..........................................................................................................7
Figure 3. The play-method with the parameter c4...........................................................................8
Figure 4. Keyboard with natural and half tone keys................................................................................9
Figure 5. Set the length of a tone using a release parameter..............................................................9
Figure 6. Pitch as conventional (c5) and MIDI (72) description.............................................................10
Figure 7. The comment in the first line starts with the hash.................................................................12
Figure 8. Two commands in Sonic Pi: "play" and "sleep"......................................................................13
Figure 9. Automatic code completion in Sonic Pi..................................................................................13
Figure 10. Parameters are given to the methods "play" and "sleep"....................................................14
Figure 11. Sound prophet..................................................................................................................16
Figure 12. All synths from Sonic Pi........................................................................................................16
Figure 13. The repeat loop in Sonic Pi...................................................................................................17
Figure 14. Code Editor with scroll bars.................................................................................................19
Figure 15. Extra MBR commands..........................................................................................................20
Figure 16. Incorrect code in line 10......................................................................................................22
Figure 17. The choose method selects from the values 60, 61, and 61................................................25
Figure 18. The parameter of the <play> method and there meaning...................................................29
Figure 19. Envelope parameters of the <play> method........................................................................30
Figure 20. Cue and Sync........................................................................................................................33
Figure 21. Effects in Sonic Pi.................................................................................................................36
Figure 22. Help for the distortion effect...............................................................................................37
Figure 23. Variables..............................................................................................................................41
Figure 24. Unknown variable and error message while program execution.........................................42
Figure 25. Variable as loop parameter..................................................................................................43
Tables
Table 1: Simple commands for the first song in Sonic Pi.........................................................................6
Table 2. The elements of the Sonic Pi interface......................................................................................7
Table 3: Learned for programming - part 1.............................................................................................8
Table 4. Modification of the pitch...........................................................................................................9
Table 5. MIDI numbering......................................................................................................................11
Table 6: Learned for programming part 2..........................................................................................14
Table 7: Learned for programming - 2...................................................................................................18
Table 8. MRB commands......................................................................................................................21
Table 9. Methods for generating random numbers..............................................................................24
Table 10: Learned for programming.....................................................................................................56
Code
Code 1. The very first example...............................................................................................................5
Code 2. Midi example...........................................................................................................................10
Code 3. Comments...............................................................................................................................12
Code 4. Song 2......................................................................................................................................16