Rendering and playing audio files with HTML5 and Jquery

Playing audio files in a rails app is very simple. By following just a few steps, you can embed an audio file in your html and use jquery to play those files in response to certain events. We'll be using the example of a simple rails app, amiruby.com, that answers "Yes" or "Nope" to the question of whether or not a site is builtwith ruby. We want our user to hear a chorus of cheers if the answer is "Yes" and a chorus of boos if the answer is "Nope".

1. Add the audio files to your app
In the public directory of your rails app, creates an audios subdirectory. This is where we will store cheers.mp3 and boos.mp3.

2. Embed the audio files in your html document

<audio class="audios" id="yes-audio" controls preload="none"> 
   <source src="audios/cheers.mp3" type="audio/mpeg">
</audio>

<audio class="audios" id="no-audio" controls preload="none"> 
   <source src="audios/boo.mp3" type="audio/mpeg">
</audio>

We gave our audio tags an id of 'audios' which we'll set to display: none; in our css file. This way the audio player will be hidden from the viewer.
3. Write the javascript

In brief, submitting a search request on this site sends an ajax post request (using remote: true) to the create method of our Searches controller. The Searches controller renders the create.js.erb view. This view contains the javascript that we want to fire on the completion of that post request.

At the completion of our post request, once we have the result (the "Yes" or "Nope" answer), we want to play the appropriate audio file:

var result = $('#result')

result.hide().html('<%= j @result %>').fadeIn(250);
playAudio(result);

function playAudio(result){
  if (result.html() === "Yes"){

    $('#yes-audio').trigger('play')
  }
  else if (result.html() === "Nope."){
    $('#no-audio').trigger('play')
  }
 
}

On our index.html.erb, we have a div with an id of "result". This is where we will 'appear' our yes or no response. We've passed in the @result variable returned by the create method of the searches controller and used the .html jquery method to fill in the result div with @result.

Then, we invoke the playAudio function, which is defined below. The playAudio function examines the value of our result div. If the result is "Yes", it used the .trigger("play") jquery method to play the audio file with an id of 'yes-audio'. If it the result is "Nope", we will play the audio file with an id of 'no-audio'.

And that's it!

subscribe and never miss a post!

Blog Logo

Sophie DeBenedetto

comments powered by Disqus
comments powered by Disqus