Jam3sn
Jam3sn

Reputation: 1087

HTML Audio - negative playbackRate values not working?

I'm playing with audio in HTML and JS/JQuery in order to build a audio player. I have Play, Pause, and Fast Forward working, but not Rewind or Backwards. In the W3Schools Documentation it says:

playbackspeed Indicates the current playback speed of the audio/video. Example values:

-1.0 is backwards

So the code that I've written is as follows:

<audio id="player">
    <source src="http://www.dkedomain.com/public/podcast/shows/the-domain-episode-09.mp3" type="audio/mpeg" />
</audio>

<button class="rewind">Rewind</button>
<button class="play">Play</button>
<button class="pause">Pause</button>
<button class="twotimes">2x</button>
<button class="forward">Fast Forward</button>

<script>

    var player = document.getElementById('player');;
    player.load();

    $('button.rewind').click(function(){
        player.playbackRate = -1.0;
    });

    $('button.play').click(function(){
        player.play();
        console.log(player.currentTime);
    });

    $('button.pause').click(function(){
        player.pause();
        console.log(player.currentTime);
    });

    $('button.twotimes').click(function(){
        player.playbackRate = 2.0;
    });

    $('button.forward').click(function(){
        player.playbackRate = 3.0;
    });

</script>

How do I get this to work as documented?

Upvotes: 3

Views: 3990

Answers (1)

Michael Gaskill
Michael Gaskill

Reputation: 8042

This Stack Overflow answer for How can I play audio in reverse with web audio API? shows that setting the audio.playbackrate = -1 will work, except in WebKit-based browsers. Chrome and Safari will ignore this setting, although other browsers may support it.

An interesting thing to do might be to implement Rewind to go back a few seconds, kind of like it does with some DVR players. Something like this might work:

$('button.rewind').click(function() {
    var currentTime = player.currentTime;
    player.currentTime = (currentTime >= 3.0) ? currentTime - 3.0 : 0;
});

You could do the same with Fast Forward, as well, for symmetry of the features. Your 2x button is a good "play faster" solution, which is a good complement to this approach.

I have created a jsFiddle for this, with various other changes that you might like: https://jsfiddle.net/mgaskill/11n63g3w/

Upvotes: 2

Related Questions