How to increase and decrease the speed of a video?

Asked

Viewed 264 times

2

I would like to know how to slow down and increase the speed of the video because I would like to offer this option to the user who uses the platform!

This is the only problem I did not find a solution, all the other tools work super well for example volume, the only thing I would like to do is this speed change.

I don’t know how I would do to increase and decrease the speed of the video, but well, this is my idea:

<video id="meuVideo"><!--esse é o meu vídeo--></video>
<input type="range" id="velocidade"><!--aqui ficaria o controle de velocidade-->

My idea would be to take the value of input and convert it to video speed, I don’t know if the video speed equals the volume control, but that’s what I want. Could someone help me/explain?

1 answer

3


To control the speed of a video being displayed in the tag <video>, you can use the property playbackRate.

The pattern of this property is 1. Thus the value of 1.5 would represent 150% of the speed and 0.5, 50%, for example. Only positive values have a visual effect. A negative value, for example, would not cause the video to be displayed in reverse.


In relation to <input type="range">, you can use the attributes max, min and step, if necessary, to control behaviour. The interval between 1 and 200, for example, you will need to divide the obtained value by 100 to fit it to the expected range by playbackRate. Thus:

const input = document.querySelector('#velocidade');

input.addEventListener('change', function() {
  const rate = parseInt(this.value, 10) / 100; // Dividir por 100 para ficar no range desejado
  console.log(rate);
});
<input type="range" min="1" max="200" value="100" id="velocidade" />

I used the parseInt because the property value of any input at all times returns a string. Although Javascript does coerce for types you in this case, the behavior is not always predictable. So prefer to at all times be explicit about type conversions in Javascript. Another option would be to use the property valueAsNumber.

Then simply assign the obtained value to the video property inside the Handler of Event Listener. Sort of like this:

const input = document.querySelector('#velocidade');
const video = document.querySelector('#meuVideo');

input.addEventListener('change', function() {
  const rate = parseInt(this.value, 10) / 100;
  video.playbackRate = rate;
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.