Sie sind auf Seite 1von 61

Making Music with Sonic Pi

Hans Gruendel

An Edutainment Factory Book

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

12.4 With Construct: Echo and other Effects..................................................................................35


12.4.1 Distortion.........................................................................................................................37
12.4.2 Echo.................................................................................................................................38
12.4.3 Reverb..............................................................................................................................38
13 Variables and Arithmetic Operations.............................................................................................40
13.1 Variables.................................................................................................................................40
13.2 Controls...................................................................................................................................43
13.3 Arithmetic Operations.............................................................................................................44
14 Data Structures..............................................................................................................................46
14.1 Lists and Rings.........................................................................................................................47
14.2 Chords.....................................................................................................................................48
14.1 Scales......................................................................................................................................49
15 Functions.......................................................................................................................................51
16 Specific Terms of the Programmer.................................................................................................56
17 Specific Terms of the Musician.......................................................................................................57

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

3 The First Song


Programmers know the "Hello World" as the very first instance, if they learn a programming
language. However, we make music here, and are therefore playing the first song (see Figure 1).

Figure 1. The Graphical User Interface of Sonic Pi with a simple example

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.

Table 1: Simple commands for the first song in Sonic Pi

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.

4 The Graphical User Interface


The graphical user interface (GUI) makes the introduction into Sonic Pi especially simple (Figure 2).
It's all together, what is needed for a quick start. The music can be started, stopped, saved and
recorded by pushing the appropriate buttons.

Music Control

Preferences

Y,.

Code Editor

Log Viewer

Workspace Tabs

Help Selection

Help Viewer

Figure 2: GUI elements of Sonic Pi

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.

Learned for programming


Nr.
1

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 Music Theory very simple


Music theory is perhaps already said too much at this point. We are talking about the pitch and
tone length.

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.

Figure 3. The play-method with the parameter c4

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

Figure 4. Keyboard with natural and half tone keys

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

Table 4. Modification of the pitch

5.2 Length of the Tone


The tone length is controlled in Sonic Pi with a whole set of parameters of the "play" method. How
long the note is held, is set via the "Release" parameter. For example, with "Play: c5, Release: 1.3", a
note is kept for 1.3 seconds. Figure 5 shows an example. First, the release parameter is set to the
value 1, that is 1 second, and thereafter to the value 2.

Figure 5. Set the length of a tone using a release parameter

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.

Figure 6. Pitch as conventional (c5) and MIDI (72) description

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

Table 5. MIDI numbering

6 The Syntax of Sonic Pi


The code editor displays everything that makes the song. And that's all in English. The different colors
also stands out. The colors indicate to the type of command itself.

6.1 Coding Types


6.1.1

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

that should be done


Writing comments is basically good Write
comments in English as possible
Writing comments in English whenever possible
Explain music and code with comment

that should be left


Write comments in German

6.1.2

Commands

Commands appear in Sonic Pi in black color. In Figure 8, two commands can be seen: "play" and
"sleep".

Figure 8. Two commands in Sonic Pi: "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).

Figure 9. Automatic code completion in Sonic Pi

that should be done


When I am quite sure, I write the command.
When I am unsure, then I use the automatic
code completion function.

that should be left


Commands written in capitals. In Sonic Pi all
commands are written in lower case.
Try to guess a complete command. There is an
automatic completion functionality.

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".

Learned for programming


Nr.
1

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.

7 A simple Melody with different Sounds


This time we want to program a simple melody in Sonic Pi. So a sequence of tones, controlled by
pitch, length and breaks. Then we change the sound.
But first the melody. You can simply copy the Code 4 into Sonic Pi editor window.

################################
#
# 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

play :b5, release: 1


sleep 1
play :a5, release: 1
sleep 1
play :g5, release: 2
sleep 2
Code 4. Song 2

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.

Figure 11. Sound prophet

Need to know what synthesizers are present at all, please visit the tab "synths", see Figure 12.

Figure 12. All synths from Sonic Pi

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.

Figure 13. The repeat loop in Sonic Pi

The loop command works like this:


1. Ahead the part to loop I write "n.times do", with "n" indicating the number of repetitions.
2. Behind the part to loop I write "end".
3. The intermediate lines I indent. For this I use 2 spaces or equally the "Tab" key.
I can summarize therefore Part 1 and Part 2, see Code 5. The 2 points at the beginning of each line
within the repeat loop indicates the indentation.

################################
#
# 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

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
end
Code 5. Part 1 and 2 of Song 2 combined in a loop

Learned for programming


No
1
2

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

that should be done


Every now and then, you should indent the code
automatically. The ALT + M should be used
frequently. You can easily detect whether the
song is structured properly.

that should be left


It is a waste of time to indent the code by hand.

8 The Code Editor


8.1 Line Numbers
Sonic Pi indicates the line numbers. That's good for orientation in coding. But even more important
are the line numbers if an error message appears. Because each message also includes the line
number, so you know in which line the error occurs, see Chapter 9.

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).

Figure 14. Code Editor with scroll bars

8.3 Right Mouse Button (MBR)


With the right mouse button one can often show commands that fit the current situation. If you click
with the right mouse button in the code editor, then a menu with the entries and shortcuts will
appear (see Figure 15).

Figure 15. Extra MBR commands

Nr.

Command

Undo

Keyboard
Shortcuts
Alt +Z

Redo

Meaning

Application

Undo the last


command

Imagine that you've


changed something in
the code and then
realize that it was not a
good idea. You could
now make the change
manually undone. Much
easier and safer to use
the "Undo" command.
You can do the
command multiple times
consecutively.

Alt +<Shift>+ Z

Making the undo


command yet

Cut

Alt + X

Copy

Alt + C

Paste

Alt +V

Cut out the marked


area
Copy the marked
area
Insert the cut or
copied range at the

You've just undo a whole


series of commands by
pressing Alt + Z, then
realize, however, that it
was one too many.
Instead of reconstructing
the past now tedious,
you can restore it with
redo.
These 3 commands
belong together and
indeed pairs: Cut and
paste or copy and paste.
For example, if you have
a good drum track in a

point where the


cursor is

Delete

Delete the marked


area

Select All

Alt + A

Select all on this


tab

song and want to use it


in another, then you
copied from one editor
tab and inserted in
another.
You can also simply press
the "Del" key on the
keyboard.
If you ever wish to
cancel all or copy all,
then you can mark
everything beforehand

Table 8. MRB commands

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.

that should be done


Before long searching in the main menu, just
look in the context menu. There you will find the
currently most important commands.

that should be left


Try to memorize the commands that are hidden
behind the MBR.

8.4 Copy and Paste

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.

Figure 16. Incorrect code in line 10.

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

that should be done


Before long wondered whether something is
right or wrong, you should try it and check the
error message in case of problems.
In Sonic Pi error messages are always in English.
This is also the case in many other languages and
that's a good thing. If you do not understand the
error message, the best to do would be to copy
it into the search engine of of the internet.

that should be left


Not check the error message exactly, and then
try to guess the error

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.

10.1 Random Numbers


In Sonic Pi the method rrand can be used for generating random numbers. You can just try it.
################################
# Random control
# Hans Gruendel
# 18.08.2015
#
################################
play rrand(50, 70)
Code 6. Method rrand for generating random numbers.

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

Table 9. Methods for generating random numbers

Example
use_random_seed 5

sleep rrand(0.2, 0.5)

sleep rand

play rrand_i(40, 50)


play rand_i(50)

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

10.3 Random Song


"Normal" songs include not really random elements and therefore often sound quite static - such as
canned. We know small random deviations from live performances of bands or individual musicians.
Everyone using Sonic Pi is aware of the static character of this songs.
Random elements are introduced to avoid this. One example is given in Code 9. Listening to this song
seems unfamiliar, and even unwieldy for the ear first. This changes during repeated listening. Then
the own charm of this method are disclosed.

################################
# 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

define :harmonics do |num, tonics, co=80, res=0.1, amp=1|


use_synth :fm
num.times do
play chord(tonics.choose, :m11).choose, res: res, cutoff: rrand(co - 40, co + 20), amp: 0.5 * amp,
attack: 0, release: rrand(0.5, 1.5), pan: rrand(-0.7, 0.7)
sleep [0.25, 0.5, 0.5, 0.5, 1, 1].choose
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".

11 Parameter: Synth and Sample


Parameters specify how a method would do it task. That something needs to be done will be
controlled by the method call itself, here it's all about the how. The code 10 is a simple example of
this. Let's look at the <play> method.

################################
# 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.

Figure 19. Envelope parameters of the <play> method

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.

that should be done

that should be left

Parameters are so important. In Sonic Pi


parameters are defined by the name.

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.

12.2 Cue +Sync: Give Inserts


In a piece of music, the individual parts are always related to each other. And sometimes they are
played even simultaneously. This is for example in the various instruments of the song of the case.
And sometimes they are attached to each other. A typical example is the change from verse and
chorus.
With the commands "cue" and "sync" you can now enter in Sonic Pi inserts. "Cue" gives the insert
and "sync" will retrieve it.
Using a parameter for the commands "cue" and "sync" let Sonic Pi knows what belongs together
respectively. The only parameter is therefore the name of the insert and may be arbitrary. The
following example uses the name "tick_drum".
Cue: tick_drum
sync tick_drum
"Cue" means in the music that the insert is given, for example, by a conductor. "Sync" is the
abbreviation for "synchronize" and accepts the insert. Figure 20 shows an example. Cue gives the
insert to "tick_drum".

Figure 20. Cue and Sync

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

12.4 With Construct: Echo and other Effects


Sonic Pi offers with synths and samples already a large number of sounds. Anyway, sometimes they
are not what you expect. Effects can now modify these sounds. Typical effects that occur outside of
music in everyday life, are reverb and delay. Reverb is produced in a large room when the sound is
thrown very quickly back from the walls. The echo is produced by the same mechanism, however, the
surfaces at which the sound is reflected is much farther away, such as rock walls in the mountains.
Sonic Pi makes effects usable by the command <with_fx>. As can be seen in Code 14, <with_fx> is
used by a block. It starts with <with_fx: effect name do> and ends with <end>.

################################
# 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.

Figure 21. Effects in Sonic Pi

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

Figure 22. Help for the distortion effect

Now about the possible parameters of distortion:


amp
We know this parameter already from the command "play". Here, as there is "amp" an abbreviation
for "amplifier" and referred to the gain of the sound. Values between 0 and 1 are possible. As you can
imagine, means amp = 0 that we will hear no distortion while amp = 1 is the normal volume that is
already preset.
mix
Sets the ratio of original sound and the distorted sound. 0 means that only the original sound is
heard, 1, only the distorted sound is heard. The default value is 0.5.

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.

that should be done


When a song consists of parallel parts, i.e. for
example of several voices, then you should
structure these in threads.
Repeating structures exist in almost every piece
of music. Avoid these repetitions in the code.
Always use loops.

that should be left


Distribute successive parts that belong together
quite clear to several threads.

13 Variables and Arithmetic Operations


So far we have been able to make a lot in Pi Sonic but still had no contact with variables. In other
programming languages this is different. Since variables are extremely important. This chapter
explains how variables are used.

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.

Figure 23. Variables

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.

Figure 25. Variable as loop parameter

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.

Figure 26. Using controls to modify 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

13.3 Arithmetic Operations


From the math classes we already know some operations, only we call them the 4 basic arithmetic
operations. So these are:
plus: +
minus: times: *
divided: /
All of these arithmetic operators can be used between variables or numbers. Figure 27 shows an
example of the addition of two numbers. In the log viewer it can be seen that a total of 3 seconds
waiting time happens until the second note is played.

Figure 27. Arithmetic Operation

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

that should be done


Variables should have self-explanatory names.
Names like "sound_piano" are good.

that should be left


Variables should have English, self-explanatory
name. Names such as "S1" or "Klavier_Klang" are
not good.

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.

14.1 Lists and Rings


A list is a series of values or variables enclosed in square brackets and separated by a comma and
could look like this:
[50, 55, 60]
This list contains 3 values with the command:
play [52, 55, 59]
you can play all the values simultaneously. So this one line will replace the three lines:
play 52
play 55
play 59
With a list so you can already save typing. But list values need not be numbers. I can also assign a
value to a variable in advance and then plug into a list:
eton = 50
play [eton, 60]
Sometimes you have a bigger list and just want to use from that a single value. There is a simple way
in Sonic Pi to do so. If you want to use, for example, the third value of a list, then use an index by
putting a 2 into the brackets behind the list name:
play [eton, 60, 66, 70][2]
Actually, you might think to used a [3] to access the third element. But do not forget the 0. [0]
therefore points to the first element, [1] to the second, [2] to the third and so one.
That seems a bit awkward at first glance, because instead of
play [eton, 60, 66, 70][2]
you could write directly
play 70
But lists always make sense if the elements were gathered together anyway and you want to access
them via a variable.
Lists have a beginning and an end. But if they are formed to a circle, then they are called a ring. Rings
are also data structures in Sonic Pi. For them there is no end. Accordingly, you can access elements of
them over any high index - even if only a very limited number of items available. And how works
that? Very easily. With each new encirclement of the ring, the index is not even set to zero, but
simply continues to be counted. If you have for example a ring having 4 elements, then the first

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.

Figure 28. C major and C minor triads

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.

Figure 30. The C major scale is played

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.

Figure 31. An astonishing number of scales are available in Sonic Pi

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.

Figure 32. The function sound1

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.

define :sound1 do |num, length = 0.1|


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 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

that should be done


Functionality that is used at several locations
should be packed in a function.
Functions should have a meaningful name.
Good style is to put in front of each function a
comment that explains the function.

that should be left


Never put the same code to different locations.

Learned for programming


No
1

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.

16 Specific Terms of the Programmer


Arguments
The values passed to a function to control the behavior of it.

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.

17 Specific Terms of the Musician


Chord
Several notes are played together and have their own characteristics. An example is the major triad.

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

Figure 26. Using controls to modify parameters...................................................................................44


Figure 27. Arithmetic Operation...........................................................................................................45
Figure 28. C major and C minor triads..................................................................................................48
Figure 29. All available chords in Sonic Pi are visible after pressing the comma key.............................49
Figure 30. The C major scale is played..................................................................................................50
Figure 31. An astonishing number of scales are available in Sonic Pi....................................................51
Figure 32. The function sound1............................................................................................................52
Figure 33. The function sound1 is called in line 9 with to few parameters...........................................54

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

Code 5. Part 1 and 2 of Song 2 combined in a loop..............................................................................18


Code 6. Method rrand for generating random numbers......................................................................23
Code 7. Method rrand for generating random numbers with seed in advance....................................24
Code 8. Method choose for the random selection...............................................................................25
Code 9. Random song...........................................................................................................................28
Code 10. Parameter of the <play> method...........................................................................................28
Code 11.in_threads command code.....................................................................................................32
Code 12. Cue and Sync example...........................................................................................................34
Code 13. Loops.....................................................................................................................................35
Code 14. With_fx used for the echo effect...........................................................................................36
Code 15. Variables................................................................................................................................41
Code 16. Addition of a number and a variable.....................................................................................46
Code 17. Scales.....................................................................................................................................50
Code 18. Example of a function............................................................................................................53
Code 19. Function with 2 variables.......................................................................................................53
Code 20. Default of arguments.............................................................................................................55
Code 21. Function and ring structure...................................................................................................55

Das könnte Ihnen auch gefallen