Amit Verma
Amit Verma

Reputation: 41249

Html audio play/pause using a single button

To play/pause an audio file on Web page I am currently using two different buttons one for playing the audio and the other for pausing the audio.

Here is the code I am using :

<button onclick="playSong()">Play
</button>

<button onclick="pauseSong()">Pause
</button>

Javascript :

<script>


var song=document.getElementById("ad");
function playSong()
{
song.play();
}

function pauseSong()
{
song.pause();
}
</script>

I want to use a single button that will play/Pause the audio, for example : on the first click the Audio will start playing and the second click will Pause the audio.

Is this possible to combine these two buttons so that I can handle the audio using a single button?

Upvotes: 1

Views: 5102

Answers (2)

Brynn
Brynn

Reputation: 127

i myself used this code for a school exercise

<!doctype HTML>
<html>
<head>
    <title>Java Script</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        function Play()
        {
            var myVideo = document.getElementById("Video1");
            if(myVideo.paused)
            {
                myVideo.play();
                //document.getElementById("play").innerHTML="Pause";
            }
            else
            {
               myVideo.pause();
               //document.getElementById("Pause").innerHTML="Play";
            }
        }
    </script>
</head>
<body>
    <button type="button" onClick="Play()">Play/Pause</button>
    <video width="320" height="240" id="Video1">
        <source src="Simple%20Plan%20-%20Last%20One%20Standing%20(Lyric%20V%C3%ADdeo).mov" type="video/mov">
        <source src="Simple%20Plan%20-%20Last%20One%20Standing%20(Lyric%20V%C3%ADdeo).mp4" type="video/mp4">
    </video>
</body>
</html>

this is my complete code hope this helps

i think the problem why it doesnt work in your code is because it says

if (song.pause)

instead of

if (song.paused)

Upvotes: 1

David
David

Reputation: 34475

var song=document.getElementById("ad");
function togglePlayPause()
{
    song.paused? song.play() : song.pause();
}

Upvotes: 3

Related Questions