S. Sterud
S. Sterud

Reputation: 23

HTML - How to play and pause audio when clicking an image?

I've tried a code that I found here on this website, but for some reason it won't work. Hope someone here could help. It plays the song when I click the gif, but when I click the gif again, it just replays it.
Here's the code I used:

<img src="lilgif.gif" alt="Play Button" onclick="StartOrStop('boss.mp3')">

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

Script:

function StartOrStop(audioFile) {
var audio = document.getElementById("myAudio");
if (!audio.src || audio.src !== audioFile) audio.src = audioFile;
if (audio.paused == false)
    audio.pause();
else
    audio.play();
}

Upvotes: 2

Views: 5359

Answers (2)

CodeSmith
CodeSmith

Reputation: 3197

Have this working example I made:

workign audio play pause on image

HTML:

<img id="startOrStopImg" src="http://wallpaper-gallery.net/images/dope-pictures/dope-pictures-17.jpg" alt="Play Button">
<audio id="audio" src="http://www.soundjig.com/pages/soundfx/futuristic.php?mp3=scifi21.mp3" type="audio/mp3" controls>
Your browser does not support the audio element.
</audio>

You can use with controls or without if you prefer to only interact with picture. Don't forget, older browsers don't have HTML5 audio, you should always place a text, image or something to tell user where is the problem. Good thing you did so with image (that one is in case image is broken or accessibility options enabled in browser)

Nothing special here only I put some ids for easy orientation and real file you can test on hosted remotely.

JS:

document.getElementById("startOrStopImg").onclick = function() {
    var audio = document.getElementById("audio");
    if (audio.paused) audio.play();
    else audio.pause();
};

Basically, I bound function defensively (this is prefered to in HTML onclick binding) and written an anon function to handle it all as a value, since I am not using it elsewhere.

It simply accesses audio elements API to check if playing then either plays or pauses.

EDIT: I have fixed and put a remotely hosted image also for a complete example. Looks way better now.

Upvotes: 3

WouldBeNerd
WouldBeNerd

Reputation: 687

can you enclose your if else statement in curly brackets please like this.

if (audio.paused == false){
      audio.pause();
}else{
      audio.play();
}

Upvotes: 1

Related Questions