Search code examples
javascriptinstancep5.js

p5js AudioIn function not working on instance mode


I was converting my p5js code to instance mode to run 2 canvases in the same DOM but my p5.AudioIn() function is not working. The error I get is referencing Failed to construct 'AudioWorkletNode'. I have uploaded a screenshot of the error below because it has more information about it. Why isn't AudioIn not working when converted to instance mode but works on global mode.

enter image description here

let s2 = function(sketch) {
  sketch.quinnListenMic;

  sketch.setup = function() {
    let cnv = sketch.createCanvas(300, 300);
    cnv.mousePressed(sketch.userStartAudio);
    sketch.quinnListenMic = new p5.AudioIn(); //ERROR HERE
    sketch.quinnListenMic.start();
  }

  sketch.draw = function() {

    sketch.background(100)

    sketch.micLevel = quinnListenMic.getLevel();
    console.log(micLevel)

  }

}

var myp5_2 = new p5(s2);
<html>

<head>
  <script defer src=https://cdn.JsDelivr.net/npm/p5></script>
  <script defer src=https://cdn.JsDelivr.net/npm/p5/lib/addons/p5.dom.min.js></script>
  <script defer src=https://cdn.JsDelivr.net/npm/p5/lib/addons/p5.sound.min.js></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
</head>

<body>
</body>

</html>


Solution

  • There were a couple of issues, fixed below with comments:

    let s2 = function(sketch) {
      // sketch.quinnListenMic; doesn't make sense. 1) You don't want to store your variables on the p5 instance, and 2) that statement doesn't actually do anything
      // This is how you declare a local variable for use in setup/draw functions:
      let quinnListenMic;
    
      sketch.setup = function() {
        let cnv = sketch.createCanvas(300, 300);
        cnv.mousePressed(sketch.userStartAudio);
        quinnListenMic = new p5.AudioIn(); //ERROR HERE
        quinnListenMic.start();
      }
    
      sketch.draw = function() {
        // Fixed local variable declaration again
        // Note: there is a bug with AudioIn.getLevel not working in all browsers
        let micLevel = quinnListenMic.getLevel();
        // Let's not spam the console log
        // console.log(micLevel)
        sketch.background(sketch.map(micLevel, 0, 1, 0, 255));
      }
    }
    
    var myp5_2 = new p5(s2);
    <html>
    
    <head>
      <!-- Your script tags were not valid -->
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js"></script>
      <!-- For some reason p5.sound does not work with the defer attribute -->
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/addons/p5.sound.min.js"></script>
    </head>
    
    <body>
    </body>
    
    </html>