init
This commit is contained in:
commit
d98ba1a7cc
47
AVcontrolsync.js
Normal file
47
AVcontrolsync.js
Normal 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
14
example.html
Normal 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
BIN
example.mp3
Normal file
Binary file not shown.
6
readme.md
Normal file
6
readme.md
Normal 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.
|
Loading…
Reference in a new issue