javascript - How can I play audio elements in sync with key presses? -
html
<textarea id="words" name="words"></textarea> <audio id="type" src="type.mp3"></audio>
js
document.getelementbyid('words').onkeydown = function(){ document.getelementbyid('type').play(); }
i want make type.mp3 play anytime press key.
but, not played in sync key.
i looking pure js solution.
the audio media element depends on buffering mechanism of browser , may not play instantly when play called.
to play sounds in sync key-presses have use web audio api instead allows play in-memory buffer , therefor instantly.
here example of how can load , trigger sound:
window.audiocontext = window.audiocontext || window.webkitaudiocontext; var request = new xmlhttprequest(), url = "https://dl.dropboxusercontent.com/s/8fp1hnkwp215gfs/chirp.wav", actx = new audiocontext(), abuffer; // load file via xhr request.open("get", url, true); request.responsetype = "arraybuffer"; request.onload = function() { // asynchronously decode audio file data in request.response actx.decodeaudiodata(request.response, function(buffer) { if (buffer) { abuffer = buffer; // keep reference decoded buffer setup(); // setup handler } } ) }; request.send(); // setup key handler function setup() { document.getelementbyid("txt").onkeydown = play; } // play sample - new buffer source must created each time function play() { var src = actx.createbuffersource(); src.buffer = abuffer; src.connect(actx.destination); src.start(0); }
<textarea id=txt></textarea>
(note: there seem bug in firefox @ time of writing reporting column not exist in code @ send() call - if problem, try code in chrome).
Comments
Post a Comment