Happylab Logo
Published on

Day28: Video Speed Controller

Authors

Introduction: How to implement video playback speed control using JavaScript.

Project Page: https://iris1114.github.io/javascript30/28_Video-Speed-Controller/

HTML

  • Contains a div container with a video element and a div element to control playback speed.
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Video Speed Scrubber</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <div class="wrapper">
      <video
        class="flex"
        width="765"
        height="430"
        src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4"
        loop
        controls
      ></video>
      <div class="speed">
        <div class="speed-bar"></div>
      </div>
    </div>

    <script src="scripts.js"></script>
  </body>
</html>

CSS

  • Sets basic page styles, including fonts, colors, and layout.
  • Styles for the video playback speed control.
body {
  font-family: 'Arial', sans-serif;
  line-height: 1.6;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #333;
  color: #fff;
}

.wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.speed {
  width: 50px;
  height: 430px;
  background: rgba(255, 255, 255, 0.1);
  margin-top: 20px;
  cursor: ns-resize;
  position: relative;
}

.speed-bar {
  width: 100%;
  background: linear-gradient(to bottom, #ff0000, #ff9900);
  text-align: center;
  color: #fff;
  font-size: 1.2rem;
  position: absolute;
  bottom: 0;
}

JavaScript

  • Uses JavaScript to implement video playback speed control.
const speed = document.querySelector('.speed')
const bar = speed.querySelector('.speed-bar')
const video = document.querySelector('.flex')

// Triggered when the mouse moves
function handleMove(e) {
  const y = e.pageY - this.offsetTop
  const percent = y / this.offsetHeight
  const min = 0.4
  const max = 4
  const height = Math.round(percent * 100) + '%'
  const playbackRate = percent * (max - min) + min
  bar.style.height = height
  bar.textContent = playbackRate.toFixed(2) + '×'
  video.playbackRate = playbackRate
}

speed.addEventListener('mousemove', handleMove)

Note

  • Uses mousemove event to listen for mouse movement.
  • Uses e.pageY to get the vertical position of the mouse.
  • Uses video.playbackRate to set the video playback speed.