A Random Sapien
[ Home | Log | Posts | Notes | Media | About ]

Coding Music with Sonic Pi

A Simple Beat

Once the program is installed and open, copy and paste the following code into the interface:

live_loop :snare do
  sample :drum_snare_hard
  sleep 0.5

Press the Play button in the upper left hand corner to run the sample, or use the keyboard shortcut Alt-R (Meta-R). This will create a snare drum beat every half second. To stop the sample, use the stop button or keyboard shortcut Alt-S (Meta-S).

Playing Notes and Chords

The following code will play a middle C.

play 60

You can also specify the note to play a different syntax

play :C

Play a C Major chord

play chord(:C, :major)

One can also define a note to play in hertz where it will be converted back to midi format. The following lines of code all play the same middle C

play hz_to_midi(261.625565)
sleep 1

play 60
sleep 1

play :C

Changing Synths

Sonic Pi comes with an assortment of synths. You can see them all by running

print synth_names

This will return a list like this:

(ring :beep, :blade, :bnoise, :chipbass, :chiplead, 
:chipnoise, :cnoise, :dark_ambience, :dpulse, :dsaw, 
:dtri, :dull_bell, :fm, :gnoise, :growl, :hollow, 
:hoover, :mod_beep, :mod_dsaw, :mod_fm, :mod_pulse, 
:mod_saw, :mod_sine, :mod_tri, :noise, :piano, 
:pluck, :pnoise, :pretty_bell, :prophet, :pulse, 
:saw, :sine, :sound_in, :sound_in_stereo, :square, 
:subpulse, :supersaw, :tb303, :tech_saws, :tri, :zawa)

This is a list of all the built-in synths that are available by default.

use_synth :mod_saw

play 60

Sounds nice! Makes me want to create some synthwave music.

the play function can also take arguments. To play a sound at half the amplitude, use the amp argument thusly.

play 60, amp: 0.5

Other Play Arguments

ADSR Diagram from Wikipedia


This example has it all

use_synth :dsaw

play 60, attack: 1, decay: 1, sustain: 1, release: 1

pan can be used to shift which the sound from right/left stereo channel. This sound, for example, will jump between ears.

play 60, pan: 1
sleep 1
play 60, pan: 0.5
sleep 1
play 60, pan: -0.5
sleep 1
play 60, pan: -1

More to come as I continue my learning!

Other Resources and Tutorials

Keyboard Shortcuts

The Official Sonic Pi Tutorial is a great resource for getting started. This web page is a copy of the documentation that comes with the program.

mehackit Creative Programming Workshop with Sonic Pi

Getting Started with Sonic Pi from the Raspberry Pi foundation website.

Example Code

A nice github gist of useful code snippets

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.