# Playing Sounds in Rails with the Audio API

*Published on February 21, 2024*

---


This is the second article in the series where we read&nbsp;[Campfire](https://once.com/campfire)'s source code to understand and extract useful techniques, practices and patterns. In today's article, we'll learn how you can play sounds in your Rails application using the Audio API.

_Check out the first article here:_ [_Custom URL Helpers in Rails with the direct Method_](/direct-custom-url-helpers-rails)[  
](/direct-custom-url-helpers-rails)

Before we begin, you should know that playing sounds on a website is pretty simple, all you have to do is this:

```javascript
const sound = new Audio("/audio.mp3")
sound.play()
```

What's more interesting is how Campfire uses the Audio API combined with Stimulus and Rails to accomplish this:

<video controls preload="metadata" src="/media/b39d460q9edgyvjh6armv85k7cxe.mp4"></video>

And that's what we'll explore in this post. How Campfire parses the user input to render the audio element on the screen, which plays the sound once when posted, and anytime later when clicked.

Sounds exciting? Let's dive in.

> 💡If you don't know / haven't heard these legendary sounds, the 'wups!' is from David's&nbsp;[build a blog in 15-minutes](https://www.youtube.com/watch?v=Gzj723LkRJY)&nbsp;presentation where he launched Rails, that&nbsp;[legendary laugh](https://www.youtube.com/watch?v=lZ_DyimkS54&t=25s)&nbsp;is from Jeff Bezos and who doesn't know Steve Ballmer's&nbsp;["Developers, Developers, Developers"](https://www.youtube.com/watch?v=XxbJw8PrIkc&t=41s)?

* * *

Let's start from the very beginning. To play a sound, the user has to type&nbsp;`/play`&nbsp;followed by the name of the sound, e.g.&nbsp;`play bezos`&nbsp;and hit enter.

We'll skip the part where a controller intercepts that request, saves the message in the database, because that's standard Rails 101. Let's see what happens when the controller saves that message and displays it via a&nbsp;`_message`&nbsp;partial, which renders message presentation via a&nbsp;`presentation`&nbsp;partial.

```ruby
# app/views/messages/_message.html.erb

<%= render "messages/presentation", message: message %>

# app/views/messages/_presentation.html.erb

<%= message_presentation(message) %>
```

**The templates and partials are not this small, by the way.**&nbsp;I've removed all the extra tags and code that's not relevant to displaying a message.

The&nbsp;`message_presentation`&nbsp;function is defined in... you guessed it, the&nbsp;`MessagesHelper`&nbsp;module.

```ruby
# app/helpers/messages_helper.rb

def message_presentation(message)
  case message.content_type
  when "attachment"
    # ...
  when "sound"
    message_sound_presentation(message)
  else
    # ...
  end
end
```

The&nbsp;`message_sound_presentation`&nbsp;function is defined in the same helper and it generates the HTML containing Stimulus controller, URL to the sound asset, and action to play the sound.

```ruby
# app/helpers/messages_helper.rb

def message_sound_presentation(message)
  sound = message.sound
  
  tag.div class: "sound", data: { controller: "sound", action: "messages:play->sound#play", sound_url_value: asset_path(sound.asset_path) } do
    play_button + (sound.image ? sound_image_tag(sound.image) : sound.text)
  end
end
```

Let's see how Campfire finds the sound in the first statement,&nbsp;`sound = message.sound`. The&nbsp;`sound`&nbsp;method is defined on the&nbsp;`Message`&nbsp;model and it parses the message body&nbsp;`/play bezos`, and returns an instance of the&nbsp;`Sound`&nbsp;for with the matching name,&nbsp;`bezos`.

```ruby
# app/models/message.rb

class Message < ApplicationRecord
  def sound
    plain_text_body.match(/\A\/play (?<name>\w+)\z/) do |match|
      Sound.find_by_name match[:name]
    end
  end
end
```

It's also important to note the&nbsp;`asset_path(sound.asset_path)`&nbsp;helper which computes the asset path.&nbsp;`Sound`&nbsp;is a plain Ruby model in Campfire:

```ruby
# app/models/sound.rb (simplified)

class Sound
  attr_reader :asset_path

  def initialize(name)
    @name = name
    @asset_path = "#{name}.mp3"
  end
end
```

By the way, the .mp3 files are stored under&nbsp;`app/assets/sounds`&nbsp;directory.

The&nbsp;`message_sound_presentation`&nbsp;helper above returns the following HTML:

```html
<div class="sound" data-controller="sound" data-action="messages:play->sound#play" data-sound-url-value="/assets/wups-fbad935c.mp3">
  <button class="btn btn--plain" data-action="sound#play">
    🔊
  </button>
  wups!
</div>
```

If you're not familiar with Stimulus, I suggest you check out&nbsp;[my articles on Stimulus](/tag/hotwire). A couple of interesting things to note:

1. the message is wrapped in a&nbsp;`data-controller="sound"`&nbsp;attribute which means the&nbsp;`sound_controller.js`&nbsp;class contains the logic to play the sound.
2. the&nbsp;`data-sound-url-value`&nbsp;contains the location of the sound. This value can be accessed in the&nbsp;`sound_controller.js`&nbsp;class in the&nbsp;`this.urlValue`&nbsp;property.
3. the&nbsp;`data-action`&nbsp;on the inner HTML button instructs Stimulus to call the&nbsp;`play()`&nbsp;method on the&nbsp;`sound_controller.js`&nbsp;class whenever the user clicks this button,
4. the&nbsp;`data-action`&nbsp;on outer div instructs Stimulus to listen for the&nbsp;`play`&nbsp;event on the&nbsp;`messages_controller.js`&nbsp;class and call the&nbsp;`play()`&nbsp;method on the&nbsp;`sound_controller.js`&nbsp;class (we'll come back to it later).

The&nbsp;`sounds_controller.js`&nbsp;is a very simple Stimulus controller class that plays the sound provided via&nbsp;`urlValue`.

```javascript
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static values = { "url": String }

  play() {
    const sound = new Audio(this.urlValue)
    sound.play()
  }
}
```

So far, so good. The controller plays the sound when you click the icon button.

However, remember that Campfire also needs to play the sound when the message is displayed the very first time.&nbsp;**How does that work?**&nbsp;That's where the&nbsp;`play`&nbsp;event in the outer HTML comes into play.

The Campfire messages are displayed in a Stimulus controller with the following action.

```text
"turbo:before-stream-render@document->messages#beforeStreamRender"
```

The&nbsp;[`before-stream-render`](https://turbo.hotwired.dev/reference/events#turbo%3Abefore-stream-render)&nbsp;event is fired right before Turbo Stream renders a page update containing the message. It calls the&nbsp;`beforeStreamRender`&nbsp;method on the&nbsp;`messages_controller`&nbsp;class.

```ruby
// app/javascript/controllers/messages_controller.js

export default class extends Controller {
  async beforeStreamRender(event) {
    // ...
    this.#playSoundForLastMessage()
    // ...
  }

  #playSoundForLastMessage() {
    const soundTarget = this.#lastMessage.querySelector(".sound")

    if (soundTarget) {
      this.dispatch("play", { target: soundTarget })
    }
  }
}
```

The&nbsp;`playSoundForLastMessage`&nbsp;dispatches the&nbsp;`play`&nbsp;event, which is listened by the&nbsp;`message_sound_presentation`&nbsp;listener above, and then it calls the&nbsp;`sound#play`&nbsp;method, making the sound.

```ruby
def message_sound_presentation(message)
  tag.div class: "sound", data: { action: "messages:play->sound#play" } do
    # ...
  end
end
```

💡To learn more how two controllers can talk to each other with events, check out:&nbsp;[Cross-Controller Coordination With Events](https://stimulus.hotwired.dev/reference/controllers#cross-controller-coordination-with-events)&nbsp;in Stimulus.

