I'm making a few assumptions in this answer:
- You're using HTML5 markup
- You want a styled link "button" to trigger a sound
- You don't want to display the default HTML5 audio player
- The sound files are stored in
public/audios
- The sound file is pre-loaded on the page
Unfortunately, the Rails 3.2 implementation of audio_tag
is broken (https://github.com/rails/rails/issues/9373). So unless you're using Rails 4, you're better off using the actual HTML markup.
In this example, we're loading an mp3 file in the the default HTML5 audio player. The following snippet should be in your view file.
<audio id="sound_effect" class="audio_player" controls="false" preload="true">
<source src="/audios/TrainWhistle.mp3" type="audio/mpeg">
</audio>
Since the HTML5 audio player comes with "built-in" display chrome, you may want to position it off the page with css. In this example, you would add the following to your css file:
.audio_player {
position: absolute;
top: -999em;
{
Your link_to markup would look something like:
<%= link_to 'At Station', '#', class: 'btn btn-success btn-medium', id: 'playsound' %>
The javascript to actually play the sound will look similar to this jQuery example:
$('#playsound').on('click', function (e) {
e.preventDefault();
$('#sound_effect').currentTime = 0;
$('#sound_effect').play();
return false;
});
This example can easily be extended to support multiple files by small changes to the link_to
tag and javascript.