This commit is contained in:
Alexander Bass 2023-02-17 10:21:55 -05:00
commit d98ba1a7cc
4 changed files with 67 additions and 0 deletions

47
AVcontrolsync.js Normal file
View file

@ -0,0 +1,47 @@
"use strict";
var GLOBAL_VOLUME;
let mediaElements = [];
document.addEventListener("DOMContentLoaded", () => {
console.log("Loaded");
mediaElements = Array.from(document.getElementsByTagName("audio"));
mediaElements.push(...Array.from(document.getElementsByTagName("video")));
mediaElements = mediaElements.filter((el) => {
return el.controls;
});
console.log(`Watching: ${mediaElements.length} media elements`);
mediaElements.forEach((el) => {
el.addEventListener("volumechange", (e) => {
updateGlobalVolume(e.target.volume);
});
el.addEventListener("play", (e) => {
stopAllOtherMedia(e.target);
});
});
const cookie = document.cookie;
if (cookie) {
const volume = JSON.parse(document.cookie).vol;
updateGlobalVolume(volume);
}
}
);
function stopAllOtherMedia(playingElement) {
mediaElements.forEach((el) => {
if (el === playingElement) {
return;
}
el.pause();
});
}
function updateGlobalVolume(newVolume) {
GLOBAL_VOLUME = newVolume;
mediaElements.forEach((el) => {
el.volume = GLOBAL_VOLUME;
});
document.cookie = `{\"vol\":${GLOBAL_VOLUME}}; SameSite=None; Secure`;
}

14
example.html Normal file
View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title></title>
<script src="AVcontrolsync.js"></script>
</head>
<body>
<audio src="example.mp3" controls></audio>
<audio src="example.mp3" controls></audio>
<audio src="example.mp3" controls></audio>
<audio src="example.mp3" controls></audio>
</body>
</html>

BIN
example.mp3 Normal file

Binary file not shown.

6
readme.md Normal file
View file

@ -0,0 +1,6 @@
# HTML 5 Audio/Video controls syncer
This simple script makes it easier to use multiple `<audio>` or `<video>` elements on one page while using the browser's implementation of the element.
The script syncs the volume of all media elements elements, and preventing more than one from playing at once.
The script is a drop in solution. It automatically works with any `<audio controls>` or `<video controls>` tag in your document.
The script will also persist volume across pages through a cookie.