-1
<!DOCTYPE html> 
<html> 
<body> 

<img id="myImage" onclick="aud_play_pause()" src="../../images/off.png" alt=""/>

<audio id="myAudio">
</audio>

<script>
    function aud_play_pause()
    {
        var song = ["../Sesler/3.mp3"];
        var myAudio = document.getElementById("myAudio");
        var image = document.getElementById('myImage');
        myAudio.src = song;
        if (myAudio.paused)
        {
            image.src = "../../images/on.png";
            myAudio.play();
        }
        else if(image.src.match("on"))
        {
            image.src = "../../images/off.png";
            myAudio.pause();
        }
    }
</script>

</body> 
</html>

Hi,

I couldn't understand why it doesn't work. It is suppose to start when I click (it starts) and it is suppose to pouse when I click again (it doesn't). I think the "else if" statement doesn't work but why?

Thanks,

H. Caglar

Çağlar
  • 81
  • 2
  • 8

1 Answers1

0

You set the audio's src every time, the user click on the button. It then starts directly after loading. Move it outside of the function and don't use an array [...], but only a string:

 myAudio.src = "../Sesler/3.mp3";

Then, an else (without another condition) should be sufficient to distinguish between playing and pausing:

if (myAudio.paused) {
    image.src = "../../images/on.png";
    myAudio.play();
} else {
    image.src = "../../images/off.png";
    myAudio.pause();
}
JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
  • Thanks for answering Joachim. I did what you said but it didn't work. The button effect is working but the audio didn't even play. – Çağlar Jun 11 '16 at 20:20
  • Did you move the assignment to `myAudio.src` outside of the function? See my Fiddle https://jsfiddle.net/1Lha66vp/ to see a working example. – JSchirrmacher Jun 13 '16 at 06:39
  • It seems somehow I forgot to add the line which is in inverted commas below. Thank you for your all help. It is working perfectly =) "document.getElementById("myImage").onclick = aud_play_pause;" – Çağlar Jun 13 '16 at 13:14