0

I have a link with icon play, when I click in this icon I want to start play a sound. And in the moment that the sound starts I want to show a stop icon replacing the play icon.

I am trying to do this with this code below, but isn´t working:

jquery:

$(function(){
    function play() {
        var audio = document.getElementById('audio1');
        if (audio.paused) {
            audio.play();
        }else{
            audio.pause();
            audio.currentTime = 0
        }
    }
});
ozil
  • 6,930
  • 9
  • 33
  • 56
Oscar
  • 89
  • 1
  • 1
  • 8

2 Answers2

1

is this what you need?

I made a fiddle: http://jsfiddle.net/boqs38pf/

HTML:

<audio id="audio1" src="http://www.freesfx.co.uk/rx2/mp3s/10/11771_1410942915.mp3"></audio>

<a id="play"  href="#" onClick="play()"><i class="fa fa-play"></i></a>
<a id="stop" href="#" onClick="play()"><i class="fa fa-stop"></i></a>

Jquery:

$(document).ready(function() {
    var audioElement = document.getElementById('audio1');
    $('#stop').hide();

    $('#play').click(function() {
        $('#play').hide();
        $('#stop').show();
        audioElement.play();
    });


    $('#stop').click(function() {
        $('#play').show();
        $('#stop').hide();
        audioElement.pause();
    });
});
StevenQ
  • 182
  • 1
  • 11
  • Yes, thanks! By the way do you know how to put this more dinamic? For example if I have more than 1 sound, instead of have this: var audioElement = document.getElementById('audio1');, receive any audio element? – Oscar Nov 12 '15 at 13:01
1

To make it more dynamic for multiple audio files what you would want to do is assign each button an id with a number that would match the id of the song you want it to control. After that you need to add to the .click function some code that will get the id of the button clicked and and play the song with the relevant Id.

$('.play').click(function(){
        var i = $(this).attr('id');
        var c = parseInt(i); 
        var g = '#idofsong' + c; 
        g.play();
    });

Edit: here is a working fiddle

Also you want to use var c = i.replace(/[A-Za-z$-]/g, ""); instead of parseInt if the id contains letters