Giacomo Balli profile picture
Giacomo Balli
The Mobile Guy

Over two decades of experience at your service.
I help business owners make better decisions.

Let's Chat LinkedIn

Instant Audio (Tap Feedback)

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();'GET', "sound.mp3", true);
    request.responseType = 'arraybuffer';
    request.onload = function () {
        var audioData = request.response;
        audioCtx.decodeAudioData(audioData, function (buffer) {
                source.buffer = buffer;
                source.loop = false;
                source.onended = getSound;
                soundLoaded = true;
            function (e) {
                console.log("Error with decoding audio data" + e.err);

function playSound() {
    if (!soundLoaded) {

- 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.

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