Search code examples
javascripttouchscreenonmouseoutonmousedownonmouseup

Even onmousedown and onmouseout in Android or Ipad gadget


I am trying to make a simple music instrument with JS. The library used is Pizzicato.js. HTML element for triggering the sound is a button with onclick, onmousedown, onmouseup and onmouseout events. The first event is only for testing the function play() and stop() from Pizzicato object. And later the two events are used for more convenient interaction.

Following script is tested in notebook and also worked in Android or IPad gadgets

function demoToggleSound() {
    var eout = document.getElementById("scriptResult");
    eout.innerHTML = "";

    var sineWave = new Pizzicato.Sound({ 
        source: 'wave', 
        options: {
                frequency: 880
        }
    });

    var btn = document.createElement("button");
    btn.innerHTML = "Play";
    eout.appendChild(btn);
    btn.addEventListener("click", btnClick);

    function btnClick() {
        var t = event.target;
        if(t.innerHTML == "Play") {
            t.innerHTML = "Stop";
            sineWave.play();
        } else {
            t.innerHTML = "Play";
            sineWave.stop();
        }
    }
}

for click event, but for onmousedown , onmouseup and onmouseout events in the followiing script

function demoSimpleInstrument() {
    var eout = document.getElementById("scriptResult");
    eout.innerHTML = "";

    var baseFrequency = 880;
    var sineWave = new Pizzicato.Sound({ 
        source: "wave",
        options: {
                //frequency: baseFrequency
        }
    });

    var ratio = [1/1, 9/8, 5/4, 4/3, 3/2, 5/3, 15/8, 2/1];
    var label = ["C", "D", "E", "F", "G", "A", "B", "C"];
    for(var i = 0; i < ratio.length; i++) {
        var b = document.createElement("button");
        b.innerHTML = label[i];
        b.id = i;
        eout.appendChild(b);
        b.addEventListener("mousedown", playSound);
        b.addEventListener("mouseup", stopSound);
        b.addEventListener("mouseout", stopSound);
    }

    function playSound() {
        var t = event.target;
        var f = baseFrequency * ratio[t.id];
        sineWave.frequency = f;
        sineWave.play();
    }

    function stopSound() {
        sineWave.stop();
    }
}

it does not work. Should I change onmousedown, onmouseup and onmouseout events in gadgets with touchscreen?


Solution

  • Thank you to Jeff. And by adding following lines of script

    b.addEventListener("touchstart", playSound);
    b.addEventListener("touchend", stopSound);
    

    It does work, but unfortunately only in Google Chrome and not in Safari.