1

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/p5@1.4.0/lib/p5.js"></script>
</head>

<body>
</body>

</html>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
seriously
  • 1,202
  • 5
  • 23

1 Answers1

2

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/p5@1.4.0/lib/p5.js"></script>
  <!-- For some reason p5.sound does not work with the defer attribute -->
  <script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/addons/p5.sound.min.js"></script>
</head>

<body>
</body>

</html>
Paul Wheeler
  • 18,988
  • 3
  • 28
  • 41
  • Note, while this code will run without an error as a StackOverflow Snippet, it would appear that the iframe sandbox that StackOverflow uses prevents the microphone from working in this way. If you copy and paste this code to OpenProcessing.org or editor.p5js.org it should work. – Paul Wheeler Jul 19 '21 at 23:21