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

  audio, canvas, html, javascript, processing.js

I’ve built a pretty large game(10,000 lines of code) in Processing.js and was able to have it run inside a webpage by loading the library. Here is an example:

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

Almost everything works with my game running in the canvas, but I would like to play sounds when the player shoots. Is there anyway to play a sound based on what is happening inside the Processing.js code? For example, lets say I have a variable inside my processing.js code that changes based on whether the player is shooting or not:

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

Thanks!

Source: Ask Javascript Questions

LEAVE A COMMENT