Last active 1733180827

In HTML5, sync both video and audio with JavaScript.

Korbs's Avatar Korbs revised this gist 1733180827. Go to revision

2 files changed, 65 insertions

index.html(file created)

@@ -0,0 +1,2 @@
1 + <video controls id="main-video" src="video.mp4"/>
2 + <audio id="main-audio" src="audio.mp4"/>

script.js(file created)

@@ -0,0 +1,63 @@
1 + // Find elements
2 + var SyncVideo = document.querySelector("#main-video")
3 + var SyncAudio = document.querySelector("#main-audio")
4 +
5 + // Object for synchronization of multiple media/sources
6 + if (typeof window.MediaController === "function") {
7 + var controller = new MediaController()
8 + SyncVideo.controller = controller
9 + SyncAudio.controller = controller
10 + } else {
11 + controller = null
12 + }
13 +
14 + // Run SyncAudio and SyncVideo simultaneously
15 + SyncVideo.addEventListener(
16 + "play",
17 + function () {
18 + if (!controller && SyncAudio.paused) {
19 + SyncAudio.play()
20 + }
21 + },
22 + false,
23 + )
24 +
25 + // Pause/Play and Buffering
26 + SyncVideo.addEventListener("waiting", () => {
27 + // If SyncVideo is buffering
28 + SyncAudio.pause()
29 + })
30 + SyncVideo.addEventListener("playing", () => {
31 + // If SyncVideo is done buffering
32 + SyncAudio.play()
33 + SyncTimestamp()
34 + })
35 +
36 + SyncVideo.addEventListener(
37 + "pause",
38 + function () {
39 + if (!controller && !SyncAudio.paused) {
40 + SyncAudio.pause()
41 + }
42 + },
43 + false,
44 + )
45 +
46 + // When Media Ends
47 + SyncVideo.addEventListener(
48 + "ended",
49 + function () {
50 + if (controller) {
51 + controller.pause()
52 + } else {
53 + SyncVideo.pause()
54 + SyncAudio.pause()
55 + }
56 + },
57 + false,
58 + )
59 +
60 + // Seekbar
61 + function SyncTimestamp() {
62 + SyncAudio.currentTime = SyncVideo.currentTime
63 + }
Newer Older