Last active 1733180827

In HTML5, sync both video and audio with JavaScript.

index.html Raw
1<video controls id="main-video" src="video.mp4"/>
2<audio id="main-audio" src="audio.mp4"/>
script.js Raw
1// Find elements
2var SyncVideo = document.querySelector("#main-video")
3var SyncAudio = document.querySelector("#main-audio")
4
5// Object for synchronization of multiple media/sources
6if (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
15SyncVideo.addEventListener(
16 "play",
17 function () {
18 if (!controller && SyncAudio.paused) {
19 SyncAudio.play()
20 }
21 },
22 false,
23)
24
25// Pause/Play and Buffering
26SyncVideo.addEventListener("waiting", () => {
27 // If SyncVideo is buffering
28 SyncAudio.pause()
29})
30SyncVideo.addEventListener("playing", () => {
31 // If SyncVideo is done buffering
32 SyncAudio.play()
33 SyncTimestamp()
34})
35
36SyncVideo.addEventListener(
37 "pause",
38 function () {
39 if (!controller && !SyncAudio.paused) {
40 SyncAudio.pause()
41 }
42 },
43 false,
44)
45
46// When Media Ends
47SyncVideo.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
61function SyncTimestamp() {
62 SyncAudio.currentTime = SyncVideo.currentTime
63}