Nedim Kurt Nedim Kurt - 1 month ago 7
Javascript Question

Play or pause an audio file (onkeydown) with JavaScript

I have the following code that's working perfectly for playing an audio file when pressing on shift (KeyCode: 16).

What I want to do is to press shift again and pause the song. I should have the possibility to 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);
}

Answer

Check it the audio is paused, if it 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);
    }
});