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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -