mirror of
https://github.com/netbymatt/ws4kp.git
synced 2026-04-14 15:49:31 -07:00
music toggles on and off
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,5 +1,5 @@
|
||||
node_modules
|
||||
**/debug.log
|
||||
server/scripts/custom.js
|
||||
music
|
||||
|
||||
server/music/*
|
||||
!server/music/readme.txt
|
||||
|
||||
2
server/music/readme.txt
Normal file
2
server/music/readme.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
.mp3 files placed in this folder will be available via the un-mute button in the application.
|
||||
No subdirectories will be scanned, and music will be played in a random order.
|
||||
@@ -2,6 +2,8 @@ import { json } from './utils/fetch.mjs';
|
||||
import Setting from './utils/setting.mjs';
|
||||
|
||||
let playlist;
|
||||
let currentTrack = 0;
|
||||
let player;
|
||||
|
||||
const mediaPlaying = new Setting('mediaPlaying', 'Media Playing', 'boolean', false, null, true);
|
||||
|
||||
@@ -62,11 +64,17 @@ const toggleMedia = (forcedState) => {
|
||||
};
|
||||
|
||||
const startMedia = () => {
|
||||
|
||||
// if there's not media player yet, enable it
|
||||
if (!player) {
|
||||
initializePlayer();
|
||||
} else {
|
||||
player.play();
|
||||
}
|
||||
};
|
||||
|
||||
const stopMedia = () => {
|
||||
|
||||
if (!player) return;
|
||||
player.pause();
|
||||
};
|
||||
|
||||
const stateChanged = () => {
|
||||
@@ -94,6 +102,48 @@ const randomizePlaylist = () => {
|
||||
playlist.availableFiles = randomPlaylist;
|
||||
};
|
||||
|
||||
const initializePlayer = () => {
|
||||
// basic sanity checks
|
||||
if (!playlist.availableFiles || playlist?.availableFiles.length === 0) {
|
||||
throw new Error('No playlist available');
|
||||
}
|
||||
if (player) {
|
||||
return;
|
||||
}
|
||||
// create the player
|
||||
player = new Audio();
|
||||
|
||||
// reset the playlist index
|
||||
currentTrack = 0;
|
||||
|
||||
// add event handlers
|
||||
player.addEventListener('canplay', playerCanPlay);
|
||||
player.addEventListener('ended', playerEnded);
|
||||
|
||||
// add the tracks
|
||||
const tracks = playlist.availableFiles.map((file) => {
|
||||
const elem = document.createElement('source');
|
||||
elem.src = `music/${file}`;
|
||||
elem.type = 'audio/mpeg';
|
||||
return elem;
|
||||
});
|
||||
|
||||
// add the track to the player
|
||||
player.append(...tracks);
|
||||
console.log('tracks added');
|
||||
};
|
||||
|
||||
const playerCanPlay = () => {
|
||||
// check to make sure they user still wants music (protect against slow loading music)
|
||||
if (!mediaPlaying.value) return;
|
||||
// start playing
|
||||
player.play();
|
||||
};
|
||||
|
||||
const playerEnded = () => {
|
||||
console.log('end of playlist reached');
|
||||
};
|
||||
|
||||
export {
|
||||
// eslint-disable-next-line import/prefer-default-export
|
||||
toggleMedia,
|
||||
|
||||
Reference in New Issue
Block a user