nicenoise/script.js
Kumi 3261e761fb
feat: enhance audio handling with attribution
Audio file structures are refactored to include attribution data, which is dynamically appended to the HTML. This change centralizes the management of audio attributes and presentation, simplifying future audio feature enhancements. A new function, `updateVolumes()`, streamlines volume updates on input change events, improving code readability and maintainability.
2024-11-13 16:30:06 +01:00

73 lines
No EOL
2.6 KiB
JavaScript

const audioFiles = {
rain: [new Audio('audio/rain.mp3'), '<a href="https://freesound.org/people/inchadney/sounds/52777/">Rain.wav</a> by <a href="https://freesound.org/people/inchadney/">inchadney</a> | License: <a href="https://creativecommons.org/licenses/by/4.0/">Attribution 4.0</a>'],
fire: [new Audio('audio/fire.mp3'), '<a href="https://freesound.org/people/CountryRoadFilms/sounds/449047/">Fire Four.wav</a> by <a href="https://freesound.org/people/CountryRoadFilms/">CountryRoadFilms</a> | License: <a href="http://creativecommons.org/licenses/by/3.0/">Attribution 3.0</a>'],
};
for (const audio in audioFiles) {
audioFiles[audio][0].loop = true;
const soundControl = document.createElement('div');
soundControl.classList.add('sound');
soundControl.innerHTML = `<label>${audio.charAt(0).toUpperCase() + audio.slice(1)}</label><input class="sound-slider" type="range" min="0" max="100" value="0" id="${audio}-slider">`;
document.getElementById('sound-controls').appendChild(soundControl);
const attribution = document.createElement('li');
attribution.innerHTML = `${audio.charAt(0).toUpperCase() + audio.slice(1)} sound: ` + audioFiles[audio][1];
document.getElementById('audio-attribution-list').appendChild(attribution);
}
function toggleSound() {
if (!playing) {
for (const audio in audioFiles) {
audioFiles[audio][0].play();
playing = true;
}
}
else {
for (const audio in audioFiles) {
audioFiles[audio][0].pause();
playing = false;
}
}
}
document.getElementById('toggle').addEventListener('click', toggleSound);
const sliders = document.getElementsByClassName('sound-slider');
function updateVolumes() {
for (const audio in audioFiles) {
const slider = document.getElementById(audio + '-slider');
audioFiles[audio][0].volume = slider.value / 100;
}
};
Array.from(sliders).forEach(slider => {
slider.addEventListener('input', function (e) {
updateVolumes();
})
});
document.addEventListener('DOMContentLoaded', () => {
const modal = document.getElementById('attribution-modal');
const openButton = document.getElementById('attributions-button');
const closeButton = modal.querySelector('.close-button');
openButton.addEventListener('click', () => {
modal.style.display = 'block';
});
closeButton.addEventListener('click', () => {
modal.style.display = 'none';
});
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
});
});
var playing = false;
updateVolumes();