如何在网页上的 canvas 中的 Processing.js 程序 运行 中播放声音?

How to play sound inside a Processing.js program running in the canvas on a webpage?

我在 Processing.js 中构建了一个相当大的游戏(10,000 行代码),并且能够通过加载库将其 运行 放在网页中。这是一个例子:

<!DOCTYPE html>
<html> 
  <head>
    <title>Processing.JS in Webpage</title> 
  </head>
  <body>
    <canvas id="mycanvas"></canvas> 
  </body>
  <script src="https://cdn.jsdelivr.net/processing.js/1.4.8/processing.min.js"></script> 
  <script>
  var programCode = function(processingInstance) {
    with (processingInstance) {
      size(400, 400);
      background(100,200,0)
      frameRate(60);
      noStroke()
      fill(255, 255, 0);
      ellipse(200, 200, 200, 200);
      noFill();
      stroke(0, 0, 0);
      strokeWeight(5);
      arc(200, 205, 150, 132, 0, PI);
      fill(0, 0, 0);
      ellipse(250, 180, 10, 10);
      ellipse(153, 180, 10, 10);
      mousePressed = function(){
        background(255,0,0);
        
        //how to play a sound file here?
        
      };
    }};

  // Get the canvas that ProcessingJS will use
  var canvas = document.getElementById("mycanvas"); 
  // Pass the function to ProcessingJS constructor
  var processingInstance = new Processing(canvas, programCode); 
  </script>
</html>

我的游戏 运行ning 在 canvas 中几乎一切正常,但我想在玩家射击时播放声音。有没有根据 Processing.js 代码中发生的事情播放声音?例如,假设我的 processing.js 代码中有一个变量,它会根据玩家是否在射击而变化:

//inside processing.js game code
if(playerIsShooting){
   //play sound here with processing.js or tell something else to play sound outside of my script?
}

谢谢!

Sound = new Audio('https://upload.wikimedia.org/wikipedia/commons/6/6e/%28Audio_Bahasa_Melayu%29_ibu.ogg');
     Sound.play();

Processing.JS 有一个声音库。您可以使用此代码播放您拥有 URL 的任何声音。

https://jsfiddle.net/sueyhazq/7/