addEventListener 点击时发出声音

Jaz*_*att 2 html audio canvas html5-audio

我想做的是一个“addEventListener”函数。单击画布并出现雨滴时,会发出晃动的声音。因此,无论您单击多少次,声音都会始终播放。

我不知道它叫什么,是我的教授建议的。然而,当我梳理google时,我发现的只是按钮点击或Jquery的东西。我不想要按钮,也不被允许使用 Jquery。

一如既往,我只寻求正确方向的推动。

感谢你们迄今为止给予我的所有帮助。

var canvas;
var context;
var drops = [];
var squares = [];


function Drop(x,y,color){
    this.x = x;
    this.y = y;
    this.color = color;
    this.dy = Math.random();
}


function Square(x,y,w,color){
    this.sx = x;
    this.sy = y;
    this.sw = w;
    this.color = color;
    this.qy = Math.random();
}

function init(){
    canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');

    alert("Hello!\nClick on the screen for rain drops!");

    window.addEventListener('resize', resizeCanvas, false);
    window.addEventListener('orientationchange', resizeCanvas, false);
    resizeCanvas();
    canvas.onclick = function(event){
        handleClick(event.clientX, event.clientY);
    };
    setInterval(handleClick,5);



}
function handleClick(x,y,w){
    var found = false;
    for(var i = 0; i<drops.length; i++){
        d = Math.sqrt((drops[i].x-x)*(drops[i].x-x) + (drops[i].y-y)*(drops[i].y-y));
        if(d<=5){
            drops.splice(i,1);
            found = true;
        }
}

    fillBackgroundColor();
    if(!found){
    var colors = ["#000080", "#add8e6", "blue"];
        var color = colors[Math.floor(Math.random()*colors.length)];
        drops.push(new Drop(x,y,color));
        squares.push(new Square(x,y,w,color));

    }

            for(var i = 0; i<drops.length; i++){
        drawDrop(drops[i]);
}
                for(var i = 0; i<squares.length; i++){
        drawSquare(squares[i]);
}

}


function drawDrop(drop){
    context.beginPath();
    context.arc(drop.x, drop.y, 5, 0, Math.PI);
    context.fillStyle = drop.color;
    context.moveTo(drop.x - 5, drop.y);
    context.lineTo(drop.x, drop.y - 7);
    context.lineTo(drop.x + 5, drop.y);
    context.closePath();
    context.fill();
    if (drop.y + drop.dy > canvas.height || drop.y + drop.dy < 0)
        drop.dy != -drop.dy;
    drop.y += drop.dy;
};


function drawSquare(square){
    var sw = Math.floor(4);
    var sx = Math.floor(Math.random() * canvas.width);
    var sy = Math.floor(Math.random() * canvas.height);
    context.beginPath();
    context.rect(sx, sy, sw, sw); 
    context.fillStyle = '#add8e6';
    context.fill();

};




function fillBackgroundColor(){
    context.fillStyle = 'gray';
    context.fillRect(0,0,canvas.width,canvas.height);
}
function resizeCanvas(){
    canvas.width = window.innerWidth - 20;
    canvas.height = window.innerHeight - 20;
    fillBackgroundColor();
    for(var i = 0; i<drops.length; i++){
        drawDrop(drops[i]);
    }

            for(var i = 0; i<squares.length; i++){
        drawSquare(squares[i]);
    }



}

function degreesToRadians(degrees) {
        return (degrees * Math.PI)/180;
    }
window.onload = init;

</script>
</head>
<body>
<canvas id='canvas' width=500 height=500></canvas>
</body>
Run Code Online (Sandbox Code Playgroud)

Bli*_*n67 5

单击画布或任何元素

要将事件侦听器添加到画布,您只需要元素,您可以通过多种方式从 DOM 获取它,我已经使用了getElementById它的唯一 id。然后,要添加click事件,只需附加侦听器和要调用的函数即可。

每次单击画布时都会调用 playSound。

var canvas = document.getElementById("canvasID"); // get the canvas
canvas.addEventListener("click",playSound);   // call playSound when clicked
// See below for the function playSound
Run Code Online (Sandbox Code Playgroud)

您还可以为 mousedown 和 mouseup 添加事件侦听器,因为只有在释放鼠标按钮时才会调用 click,这可能不是所需的效果。

加载声音

由于需要加载声音,这可能需要一些时间,因此您需要有一种方法来指示声音已加载并准备好播放。对于这个简单的答案,信号量就可以解决问题。只需设置一个属性来指示已加载。

var sound = new Audio();         // create the audio
sound.src = "SoundFileURL.mp3";  // set the resource location 
sound.oncanplaythrough = function(){   // When the sound has completely loaded
    sound.readyToRock = true;    // flag sound is ready to play
                                 // I just made it up and can be anything
};
sound.onerror = function(){      // not required but if there are problems this will help debug the problem
    console.log("Sound file SoundFileURL.mp3 failed to load.")
};
Run Code Online (Sandbox Code Playgroud)

重复播放声音

功能playSound。音频资源只能以一种声音的形式播放。你不能超越它本身。重复单击时,您需要重置声音播放位置,以便重新开始。为此,只需将 设为currentTime0(声音的开始)并调用方法play。这样每次点击都会启动声音或倒带并重新开始,无需检查是否正在播放。如果您希望声音重叠,则需要加载它的多个副本,并在每次单击时循环播放哪个副本。

// assuming sound is in scope from above code
function playSound(){
    if(sound && sound.readyToRock){  // check for the sound and if it has loaded
        sound.currentTime = 0;       // seek to the start
        sound.play();                // play it till it ends
    }
}
Run Code Online (Sandbox Code Playgroud)

声音重叠

从阵列中播放相同的声音,使其重叠。将相同的声音多次加载到数组中。保留一个变量,该变量将指向数组中要在用户调用该函数(通过单击事件)时播放的下一个声音,然后寻找开始并播放声音。增加下一个声音指针,为下一次单击做好准备。

这将使声音自行播放。加载声音的次数取决于用户点击的频率以及声音的时长。不要太过分,因为有一个点你无法判断新的声音是否已经开始,或者正在播放的声音是否已经重新开始。

多次加载相同的声音

var sounds = [];  // array to hold the sound
for(var i = 0; i < 4; i++){
    var sound = new Audio();         // create the audio
    sound.src = "SoundFileURL.mp3";  // set the resource location 
    sounds.push(sound);              // put the sound on the array
}
Run Code Online (Sandbox Code Playgroud)

播放声音数组

// assuming that the array sounds has the sounds you want to overlap
// and that they have been loaded so there is no need to check their status
var soundToPlay = 0; // the next sound to play

// the click event function.
function playSound(){
    var sound = sounds[soundToPlay % sounds.length]; // get the next sound
                                                     // making sure that it 
                                                     // does not go past the 
                                                     // of the array
    sound.currentTime = 0; // seek to start
    sound.play();          // play it
    soundToPlay += 1;      // point to the next sound to play
}
Run Code Online (Sandbox Code Playgroud)