Skip to main content
Published in Engineering Insights

Stringing Code Together To Play Music

Stringing Code Together To Play Music
Table of contents
  1. Ruby Software Design Concert Series
  2. Setting the Stage
  3. String Theory
  4. Why does :e2 + 1 work in Sonic Pi but not in plain Ruby?
  5. Plucking a Single String
  6. What options does the :pluck synth take?
  7. Strike a Chord
  8. How does Sonic Pi receive OSC messages from another program?
  9. What do you check when an OSC message does not reach Sonic Pi?
  10. Rock On

Ruby Software Design Concert Series#

  1. Dependency Injection: Plug In
  2. Shedding a Light on Duck Typing
  3. Synthesizing A Composition With Delegation
  4. Inheritance: Derivative Songwriting
  5. Using Sonic Pi To Play Music With Ruby
  6. Stringing Code Together To Play Music

Setting the Stage#

In our last post, I talked about how I built an interface to Sonic Pi when I was preparing my RubyConf 2020 talk about Ruby's Coverage module. At the end of that post, we could send sounds to Sonic Pi. Today, we'll have our code play the guitar, and send those sounds to our amplifier.

String Theory#

A guitar is a string instrument, and each of those strings make a sound when you play them. For this example we'll focus on the happy path, which is that plucking the string plays the expected note. The code I built also considers that strings can break, and attempting to play broken strings won't work. You can look at the full implementation to see how that works.

Plucking an individual string creates a new sound.

Ruby
class String
  def pluck(fret:)
    ...
    play_note(fret)
  end

  private

  def play_note(fret)
    StringSound.new(
      string_number: @number,
      tuning_note: tuning_note,
      fret_number: fret,
    )
  end
end

The @number variable is which string on the guitar it is, with index 0 being the low E, and index 5 being the high E, in standard tuning. The tuning_note is what note that string is tuned to, because any string can be tuned to any note. Again, for simplicity here, we'll assume standard tuning (EADGBE).

Our StringSound class converts that information into the command we'll send to Sonic Pi. All notes in Sonic Pi are represented with a number, and we can also use "traditional" note names, passed to it as a symbol. We can use that to figure out the note our string would play if you plucked it without pressing down on a fret.

Ruby
class StringSound
  def playable_note_root
    playable_note_key.dig(@string_number, @tuning_note)
  end

  def playable_note_key
    {
      0 => { e: :e2 },
      1 => { a: :a2 },
      2 => { d: :d3 },
      3 => { g: :g3 },
      4 => { b: :b3 },
      5 => { e: :e4 },
    }
  end
end

The number next to the note (the 2 in :e2 for the low E string) represents the octave.

A helpful thing here is that the note is still a number to Sonic Pi. We can add the fret number pressed on the string to the root note of the string and Sonic Pi will know what note that is. We'll construct a Sonic Pi command to send to our amplifier to play that note.

Ruby
class StringSound
  def amp_value
    "(note(:#{playable_note_root}) + #{@fret_number})"
  end
end

This is all in a string (the data type, not the part of the instrument), because we're going to pass it to Sonic Pi via the sonic-pi-cli gem.
This is going to execute the note method in Sonic Pi to play that single tone.

Why does :e2 + 1 work in Sonic Pi but not in plain Ruby?#

Sonic Pi adds its own + method to Ruby's Symbol class. The method lives in Sonic Pi's western_theory.rb file. It turns the note symbol into its MIDI number, then adds. So :e2 + 1 becomes 41. Ruby's own Symbol docs list no + method, so the same line fails in plain Ruby.

Sonic Pi's note.rb file adds the octave times 12, the note's semitones above C, and 12. A symbol with no octave, such as :e, gets octave 4. The Sonic Pi tutorial gives the anchor point: "It turns out that the C of the 4th octave (C in English notation) is identified by the number 60."

ExpressionSonic Pi givesHow
:e2402 times 12, plus 4 for E, plus 12
:e64No octave given, so octave 4: 4 times 12, plus 4, plus 12
:e2 + 141The + method resolves :e2 to 40, then adds 1
:c4604 times 12, plus 0 for C, plus 12

This post's own code reaches the same number by another path. Its StringSound builds note(:e2) + 1, so note resolves the symbol first. The + after it is plain Integer math. Either way, the result is the line this post leans on: "A helpful thing here is that the note is still a number to Sonic Pi."

Plucking a Single String#

Our guitarist is interfacing with the guitar as a whole, which is composed of many strings. They'll first place their fingers on the neck of the guitar.

Ruby
class FingerPlacement
  attr_reader :fret
  attr_reader :string_number
end

And pluck an individual string with that placement.

Ruby
class Guitar
  def pick(finger_placement, duration: 1)
    result = strings[finger_placement.string_number].pluck(fret: finger_placement.fret)
    @amplifier.play(sound_output("play #{result.amp_value}", duration: duration))
  end
end

Here our guitar is adding details to the command that we'll send to Sonic Pi. We have the information about the note to play from the string, but now we want it to sound like a note from a guitar, and we'll rely on the guitarist to say how long to play the note for (the duration).

We can do this in Sonic Pi by specifying the synthesizer to use when playing the note, and we'll choose one that sounds like a guitar.

Ruby
class Guitar
  def sound_output(play_operation, duration: 1)
    [
      "with_synth :pluck do",
      "#{play_operation}, release: #{duration}",
      "end",
    ].join("\n").strip
  end
end

If you wanted to play this directly in Sonic Pi's IDE, it would look more familiar:

Ruby
with_synth :pluck do
  play note(:e2 + 1), release: 1
end

However, we need to package this all up in a string to then send that command over to Sonic Pi via the sonic-pi-cli gem.

Our amplifier, passed in via dependency injection, then takes that command and sends it to Sonic Pi, producing a sound!

What options does the :pluck synth take?#

The :pluck synth takes a note: plus opts many synths share, such as amp: and pan:. It adds four opts that shape the pluck itself: noise_amp:, max_delay_time:, pluck_decay: and coef:. Its definition in the Sonic Pi source lists the four opts in the table below.

This post picked it for its sound: "We can do this in Sonic Pi by specifying the synthesizer to use when playing the note, and we'll choose one that sounds like a guitar." The table lists the four pluck opts as that file defines them at Sonic Pi v5.0.0.

OptionDefaultAllowed valuesWhat the docs say
noise_amp0.80 to 1, inclusive"Amplitude of source (pink) noise."
max_delay_time0.1250.125 to 1, inclusive"Maximum length of the delay line buffer."
pluck_decay301 to 100, inclusive"How long the pluck takes to stabilise on a note. This doesn't have a dramatic effect on the sound."
coef0.3Greater than minus 1 and less than 1"Coefficient of the internal OnePole filter. Values around zero are resonant and bright, values towards 1 sound more dampened and cutoff."

The note: opt accepts both forms from the section above. Its doc says: "Either a MIDI number or a symbol representing a note." To set the pluck opts, pass them as named opts, as in synth :pluck, note: :e2, coef: 0.1. The doc for synth explains that shape: "When using synth, the note is no longer an explicit argument but an opt with the key note:."

Strike a Chord#

Sonic Pi already knows how to play chords, so this could be a quick section; however, we're going to replicate that functionality a little differently. We're doing this because of the reality I mentioned when talking about strings, and that is, they can break. If a string is broken, the note in the chord that string would regularly play shouldn't be heard.

As such, we need to go string by string to determine the notes to play. Even though the reasoning is to handle broken strings, we're not going to consider that case in this explanation. You can view the full implementation to see how that's handled.

We first need to know which notes we should play:

Ruby
class Guitar
  def strum(chord, duration: 1)
    notes = [
      strings[0].pluck(fret: chord.first_fret),
      strings[1].pluck(fret: chord.second_fret),
      strings[2].pluck(fret: chord.third_fret),
      strings[3].pluck(fret: chord.fourth_fret),
      strings[4].pluck(fret: chord.fifth_fret),
      strings[5].pluck(fret: chord.sixth_fret),
    ].map(&:amp_value)
  end
end

We'll then take all of those notes and pass them to our amplifier, using Sonic Pi's play_pattern_timed method. This also allows us to define a time between each note, so we can place a small amount of time in between each to simulate the time it would take your hand to complete a downstroke across all the strings.

Ruby
class Guitar
  def strum(chord, duration: 1)
    notes = [...].map(&:amp_value)

    @amplifier.play(
      sound_output(
        "play_pattern_timed [#{pattern_notes.join(", ")}], 0.05",
        duration: duration,
      )
    )
  end
end

The 0.05 is our amount of time it'll take to pluck from one string to the next when playing a chord.

How does Sonic Pi receive OSC messages from another program?#

Sonic Pi listens on port 4560 for OSC messages from programs on the same computer, says the OSC chapter of the Sonic Pi tutorial. A live_loop picks each message up with sync and hands its values to a synth. OSC is short for Open Sound Control, a simple network protocol.

Here is the tutorial's basic listener with :pluck in place of :prophet, and two values instead of three. It runs in a Sonic Pi buffer.

Ruby
live_loop :foo do
  use_real_time
  a, b = sync "/osc*/trigger/pluck"
  synth :pluck, note: a, coef: b
end

The tutorial explains the path: "The /osc prefix is added by Sonic Pi to all incoming OSC messages, so we need to send an OSC message with the path /trigger/prophet for our sync to stop blocking and the prophet synth to be triggered." Here the sender uses /trigger/pluck instead.

The tutorial says: "We can send OSC to Sonic Pi from any programming language that has an OSC library." In Ruby, the osc-ruby gem is one such library, and 1.1.5 is its latest version on RubyGems. The calls below come from its README, and the address and port from the tutorial.

Ruby
require 'osc-ruby'

client = OSC::Client.new('127.0.0.1', 4560)
client.send(OSC::Message.new('/trigger/pluck', 41, 0.1))

Press Run on the listener first, then run the Ruby script. The 41 is :e2 + 1 from the table above. The 0.1 sets coef: near zero, where the docs say values are resonant and bright.

Code like this only makes a sound while Sonic Pi is running. The Gnar Company's dependency injection post faced that in its tests and names what drove its design: "In reality, the difficulty in testing the Guitar class is what led to the decision to inject the amplifier in." Its tests use a PracticeAmplifier that does nothing.

What do you check when an OSC message does not reach Sonic Pi?#

Check five things in order: where the sender runs, what the cue log shows, whether the paths match, which argument types you send, and which version of Sonic Pi you use.

Plan for these misses before you play live. This post says it plainly about its own guitar: "Even with these principles in place, mistakes and errors happen."

  • The sender is on another computer. The tutorial says that by default Sonic Pi does not let remote machines send it OSC messages. Turn on Preferences, then IO, then Networked OSC, then Allow OSC from other computers. The sender also needs your IP address, which the IO section of the preferences pane shows.
  • The cue log stays empty. The tutorial says an incoming OSC message is displayed in the cue log, just like incoming MIDI. If nothing shows there, check that Sonic Pi is running and the sender targets port 4560.
  • The cue log shows the message, but nothing plays. Compare the paths. In the tutorial's listener, the sync path starts with /osc*, and the sender's path leaves that prefix off. Then check that the listener buffer is running.
  • A symbol argument goes missing. The osc-ruby message class encodes Integer, Float and String arguments. A Ruby symbol such as :e2 is not one of them, so it is dropped. Send 40 instead.
  • You are in the web version. The feature table on sonic-pi.net marks "Well-timed OSC in and out" as yes for the app and no for the web. Use the desktop app for OSC.

Rock On#

Combining a few key software design principles, we were able to create a flexible, extensible, and testable system for playing music over the course of a few blog posts.

We're now armed with an amplifier that knows how to communicate with Sonic Pi
that's passed in to our guitar via dependency injection (but could send the notes anywhere as long as the injected class responds to the right methods). Our guitar is composed of various strings, each of which are responsible for knowing what sound to make.

Given a songwriter who knows how to consistently write for our band, we can play chords and individual notes on our guitar as the song requires.

If you listen closely at :14, you can hear a string break. Even with these principles in place, mistakes and errors happen. Make sure your system is prepared to handle errors in a fault-tolerant way, but that's a different blog series altogether. Thanks for joining me in this exploration.

Learn more about how The Gnar builds Ruby on Rails applications.

Frequently asked questions

How is the note for a fret calculated?

Sonic Pi treats a note as a number. Adding the fret number to the string's root note gives the note to play.

How does the note sound like a guitar?

The guitar selects the :pluck synthesizer and sets release to the requested duration.

Why build chords string by string?

A broken string should not contribute a note to a chord. The full implementation handles that case, though the explanation leaves it out.

How is a strum simulated?

The notes go to Sonic Pi through play_pattern_timed. A small amount of time between notes simulates the hand moving across the strings.

How do I test Ruby code that plays through Sonic Pi?

Pass the amplifier in, then give your tests a stand-in that makes no sound. The Gnar Company's dependency injection post does this with a PracticeAmplifier that does nothing, so its unit tests run without Sonic Pi. That post sums up the change: 'With this small change, our Guitar can work with any amplifier that responds to the play method.'

How do I play a chord or an arpeggio in Sonic Pi itself?

Sonic Pi's tutorial plays a chord with play chord(:E3, :minor), which sounds the notes together. For an arpeggio, play_pattern_timed chord(:E3, :m7), 0.25 plays them one after another. This Gnar Company post builds its chords string by string instead, because 'If a string is broken, the note in the chord that string would regularly play shouldn't be heard.'

What is the latest version of Sonic Pi?

As of November 12, 2026, Sonic Pi v5.0.0, published on August 7, 2026, is the latest release on GitHub. Its release notes say SuperSonic now fully replaces scsynth as the audio engine. The app runs on Windows, macOS and Linux, and sonic-pi.net also runs Sonic Pi v5.0 in the browser.

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.