Skip to content

Instantly share code, notes, and snippets.

@rickd-uk
Created February 13, 2022 09:58
Show Gist options
  • Save rickd-uk/338eec0120a14ac293ac518d5b6de9ad to your computer and use it in GitHub Desktop.
Save rickd-uk/338eec0120a14ac293ac518d5b6de9ad to your computer and use it in GitHub Desktop.
Ask User Permission To Allow Sound (JS)
const audio = new Audio( 'https://dl.dropboxusercontent.com/s/h8pvqqol3ovyle8/tom.mp3' );
audio.muted = true;
const alert_elem = document.querySelector( '.alert' );
audio.play().then( () => {
// already allowed
alert_elem.remove();
resetAudio();
} )
.catch( () => {
// need user interaction
alert_elem.addEventListener( 'click', ({ target }) => {
if( target.matches('button') ) {
const allowed = target.value === "1";
if( allowed ) {
audio.play()
.then( resetAudio );
}
alert_elem.remove();
}
} );
} );
document.getElementById( 'btn' ).addEventListener( 'click', (e) => {
if( audio.muted ) {
console.log( 'silent notification' );
}
else {
audio.play();
}
} );
function resetAudio() {
audio.pause();
audio.currentTime = 0;
audio.muted = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment