function - Play or pause an audio file (onkeydown) with JavaScript -
i have following code that's working playing audio file when pressing on shift (keycode: 16).
what want press shift again , pause song. should have possibility play/pause multiple times.
html:
<audio id="audio" src="audio/song.mp3" autostart="false"></audio>
javascript:
var sound = { 16: 'audio' }; document.onkeydown = function (e) { var soundid = sound[e.keycode]; if (soundid) document.getelementbyid(soundid).play(); else console.log("key not mapped : code is", e.keycode); }
check audio paused, if is, play it, otherwise pause it
var sound = { 16: 'audio' }; document.addeventlistener('keydown', function(e) { var soundid = sound[e.which || e.keycode]; if (soundid) { var elem = document.getelementbyid(soundid); if ( elem.paused ) { elem.play(); } else { elem.pause(); } } else { console.log("key not mapped : code is", e.keycode); } });
Comments
Post a Comment