1

I am trying to use p5.js sound library in Node.js and the preload function simply throws an (understandable) error saying that it is not being used. How do I use the preload function in 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;
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
William
  • 4,422
  • 17
  • 55
  • 108

1 Answers1

2

By default, P5.js uses global mode, which means that it puts functions and variables in the global scope. That's what you're doing with your preload() function.

The problem is, this doesn't always play nice with other libraries, and it looks like it's causing problems with node.js.

You can fix this problem using instance mode, which packages up the P5.js functions in an object that you can use instead of putting everything in the global scope. Here's a simple example:

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);

You can find more information in this guide.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107