Play Audio File on Button Click in Rails

So you want to play an audio clip on a button click.  In your view file

<%= audio_tag "audio.m4a", class: "audio-play" %>
<p class="btn btn-primary audioButton">Play</p>

This uses the rails audio tag, and then places a button next to it. In the javascript, you play the audio file on the button click:

$(".audioButton").on("click", function() {
  $(".audio-play")[0].currentTime = 0;
  return $(".audio-play")[0].play();
});

Or in coffeescript:

$(".audioButton").on "click", ->
  $(".audio-play")[0].currentTime = 0
  $(".audio-play")[0].play()

Some credit to this Stack Overflow question.

Advertisements

2 Responses to Play Audio File on Button Click in Rails

  1. btunbutr says:

    Thanks this was very helpful!

  2. Pingback: Mystery Movie | bryanttunbutr

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: