【问题标题】:p5js AudioIn function not working on instance modep5js AudioIn 函数在实例模式下不起作用
【发布时间】:2021-07-11 03:27:09
【问题描述】:

我正在将我的 p5js 代码转换为实例模式以在同一个 DOM 中运行 2 个画布,但我的 p5.AudioIn() 函数不起作用。我得到的错误是引用Failed to construct 'AudioWorkletNode'。我上传了下面错误的屏幕截图,因为它有更多信息。为什么AudioIn 在转换为实例模式时不工作,但在全局模式下工作。

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>

【问题讨论】:

标签: javascript instance p5.js


【解决方案1】:

有几个问题,下面用 cmets 修复:

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>

【讨论】:

  • 请注意,虽然此代码作为 StackOverflow 片段运行时不会出错,但似乎 StackOverflow 使用的 iframe 沙箱会阻止麦克风以这种方式工作。如果您将此代码复制并粘贴到 OpenProcessing.org 或 editor.p5js.org,它应该可以工作。
猜你喜欢
  • 2017-05-12
  • 2021-08-29
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多