如何使用 p5.js 声音库预加载 Node.js (和 create-react-app)

How to use p5.js sound library preload with Node.js (and create-react-app)

我正在尝试在 Node.js 中使用 p5.js 声音库,而预加载函数只是抛出一个(可以理解的)错误,指出它未被使用。如何使用 Node 中的预加载功能?

import React, { Component } from 'react';
import p5 from "p5";
import 'p5/lib/addons/p5.dom';
import "p5/lib/addons/p5.sound";
import sound from "./audio/song.mp3";
import './App.css';

let song;

function preload() { // @preload is required by P5.js
    p5.soundFormats('mp3', 'ogg');
    song = p5.loadSound(sound);
}






class App extends Component {

    render() {

        return (
            <div className="App">

               <button>Click me</button>
            </div>
        );
    }
}

export default App;

默认情况下,P5.js使用全局模式,这意味着它将函数和变量放在全局范围内。这就是您使用 preload() 函数所做的。

问题是,这并不总是与其他库一起使用,而且它似乎导致了 node.js 的问题。

您可以使用 实例模式 解决此问题,它将 P5.js 函数打包在一个对象中,您可以使用该对象而不是将所有内容都放在全局范围内。这是一个简单的例子:

var s = function( sketch ) {

  var x = 100; 
  var y = 100;

  sketch.setup = function() {
    sketch.createCanvas(200, 200);
  };

  sketch.draw = function() {
    sketch.background(0);
    sketch.fill(255);
    sketch.rect(x,y,50,50);
  };
};

var myp5 = new p5(s);

您可以在 this guide 中找到更多信息。