Search code examples
ruby-on-rails-3html5-audiolink-to

Rails link_to and audio_tag


I'm trying to figure out the best way to play a wav file in the background (HTML5-like) when I use a link_to tag in Rails.

Here's a sample link_to from one of my views:

<%= link_to 'At Station', at_station_mdt_index_path, :class => 'btn btn-success btn-medium', :method => :put, :remote => true %>

I'd like to figure out how to use the audio_tag to trigger a sound when the button is pressed. I've tried combining the audio_tag in the link_to ERB but get all sort of syntax errors.

Any examples would be greatly appreciated.

Updated 01/04/14-10:18am CT: The sounds fire once and properly. However since adding the :id to the link_to the links no longer trigger the rails path to change the object, only plays the sound

View code:

    <%= link_to 'En Route', en_route_mdt_index_path(:call_id => call.id), :class => 'btn btn-warning btn-medium', :method => :put, :remote => true, :id => "er" %>
            <%= link_to 'On Scene', on_scene_mdt_index_path(:call_id => call.id), :id => 'to', :class => 'btn btn-primary btn-medium', :method => :put, :remote => true, :id => "os"  %>
            <%= link_to 'To Hospital', to_hospital_mdt_index_path(:call_id => call.id), :class => 'btn btn-warning btn-medium', :method => :put, :remote => true, :id => "to" %>

 <audio id="en-route" class="audio_player" preload="true">
    <source src="audios/en-route.wav" type="audio/wav">
</audio>

<audio id="on-scene" class="audio_player" preload="true">
    <source src="audios/on-scene.wav" type="audio/wav">
</audio>

<audio id="to-hospital" class="audio_player" preload="true">
    <source src="audios/to-hospital.wav" type="audio/wav">
</audio>

<script>
$('#er').click(function (e) {
    e.preventDefault();
    $('#en-route')[0].currentTime = 0;
    $('#en-route')[0].play();
    return true;

});

$('#os').click(function (e) {
    e.preventDefault();
    $('#on-scene')[0].currentTime = 0;
    $('#on-scene')[0].play();
    return true;

});

$('#to').click(function (e) {
    e.preventDefault();
    $('#to-hospital')[0].currentTime = 0;
    $('#to-hospital')[0].play();
    return true;

});
</script>

Solution

  • Here's a simple example for playing a wav file:

    http://jsfiddle.net/84pav/

    HTML:

    <a href="javascript:void(0)" id="playsound">At Station</a>
    
    <audio id="sound_effect" class="audio_player" preload="auto">
        <source src="http://www.villagegeek.com/downloads/webwavs/alrighty.wav" type="audio/wav">
    </audio>
    

    JavaScript:

    $('#playsound').click(function (e) {
        $('#sound_effect')[0].currentTime = 0;
        $('#sound_effect')[0].play();
        return false;
    });
    

    I set currentTime = 0 before playing to make it always plays from the beginning.

    It does not work on IE because IE does not support wav file.