Instant Audio (Tap Feedback)
Back to main listing.
Directions:
- place your sound file in the same folder as the script (sound.mp3).
- call getSound() when the page loads to make sure it's ready to be used.
- attach playSound() to an element's touchEnd or click event.
Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.
This code sample will allow you to deliver instant (audio) feedback to the user when they tap something. Not only it's more fun and interactive to have sounds but it also make the UX more engaging (read less frustrating) because there is an acknowledgement of the user's action and intent (in case the result isn't instant and obvious).
var audioCtx = new window.webkitAudioContext(); var source; var soundLoaded = false; function getSound() { soundLoaded = false; source = audioCtx.createBufferSource(); var request = new XMLHttpRequest(); request.open('GET', "sound.mp3", true); request.responseType = 'arraybuffer'; request.onload = function () { var audioData = request.response; audioCtx.decodeAudioData(audioData, function (buffer) { source.buffer = buffer; source.connect(audioCtx.destination); source.loop = false; source.onended = getSound; soundLoaded = true; }, function (e) { console.log("Error with decoding audio data" + e.err); } ); }; request.send(); } function playSound() { if (!soundLoaded) { return; } source.start(0); }
Directions:
- place your sound file in the same folder as the script (sound.mp3).
- call getSound() when the page loads to make sure it's ready to be used.
- attach playSound() to an element's touchEnd or click event.
Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.
Published: Sat, Jan 9 2016 @ 14:49:52
Back to Blog