Search code examples
htmlhtml5-audio

I want to stop/skip 30 seconds on audio in HTML


I have an audio file in html. I want 4 buttons there: one for play,one for pause,one for stop,one for 30 seconds skip. Pause/Play works. The other 2 don't. I spent 2 hours trying and searching through internet and I simply can't understand. Here is my code.

<!DOCTYPE html>
<html>

<head>

    <script>
    function playsong() {
        document.getElementById("Player").play();
    }

    function pausesong() {
        document.getElementById("Player").pause();
    }

    function stopsong() {
        document.getElementById('Player').setcurrentTime();/**tried also with audio.currentTime here. Didn't worked **/
        audio.currentTime = 0;
    }

    function forwardAudio() {
        document.getElementById('Player').setcurrentTime(); /**tried also with audio.currentTime here. Didn't worked **/
        audio.currentTime += 30.0

    }
    </script>
</head>

<body>
    <img src="http://www.example.com/foo.jpg" height="300" width="200">
    <video width="420" height="340" controls="controls">
        <source src="http://example.com/foo.mp4" type="video/mp4" />
        <object data="movie.mp4" width="420" height="340">
            240" />
        </object>
    </video>
    <audio controls="controls" autoplay ID="Player">
        <source src="http://example.com/foo.mp3" />
    </audio>
    <button type="button" onclick="playsong()">Play</button>
    <button type="button" onclick="pausesong()">Pauza</button>
    <button type="button" onclick="stopsong()">Stop</button>
    <button type="button" onclick="forwardAudio()">Skip 30 seconds</button>
</body>
</html>

Solution

  • You did not have an audio variable. You need to grab the player and make the changes directly to the player. You also need to pause() on stopsong() or it will go back to the beginning but continue to play.

    function stopsong() {
        var player = document.getElementById('Player');
        player.pause();
        player.currentTime = 0;/**tried also with audio.currentTime here. Didn't worked **/
    }
    
    function forwardAudio() {
        var player = document.getElementById('Player');
        player.currentTime += 30.0; /**tried also with audio.currentTime here. Didn't worked **/
    
    }