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 end
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.
You can also specify the note to play a different syntax
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
Sonic Pi comes with an assortment of synths. You can see them all by running
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.
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
- Attack: The time it takes to go from muted to peak sound
- Decay: How long the run down takes after peak is reached
- Sustain: How long the peak will last
- Release: How long to go from sustain to no sound
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
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.
Getting Started with Sonic Pi from the Raspberry Pi foundation website.