Search code examples
javascripthtmlp5.js

ReferenceError: soundFormats is not defined


I am trying to learn about p5 and have been going through the tutorials (https://p5js.org/reference/#/p5.SoundFile).

function preload() {
  soundFormats('mp3', 'ogg');
  mySound = loadSound('assets/cam.mp3');
}

function setup() {
  mySound.setVolume(0.1);
  mySound.play();
}

I have followed the documentation verbatim, except for the fact that I switched in my own test song. When I run this on my repl.it https://repl.it/@JacksonEnnis/Coloquial I get an error stating "ReferenceError: soundFormats is not defined". However, I know that this function IS defined, because it is from the documentation. I have googled the problem, but it does not seem like it is a common issue to experience.

If anyone understands why this is happening, please explain it to me so I may learn.

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script language="javascript" type="text/javascript" src="path/to/p5.sound.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.9.0/p5.js"></script>
    <script src="script.js"></script>
  </body>
</html>

Solution

  • Just to sum up the comments. Here's the solution that works:

    <!doctype HTML>
    <html>
    <head>
      <html><head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/p5.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.16/addons/p5.sound.js"></script>
    
    </head>
    <body>
      <script> 
        function preload() {
          soundFormats('ogg', 'mp3');
          mySound = loadSound('https://ia802508.us.archive.org/5/items/testmp3testfile/mpthreetest.mp3');
        }
    
        function setup() {
          mySound.setVolume(1);
          // mySound.play();
          mySound.loop();
        }
      </script>
    </body>
    </html>
    

    as you can see: the p5.sound.js file has to be included as well. It has to be a valid path and it has to be loaded after the p5.js.

    soundFormats is a function defined in p5.sound.js. And if this javascript file has not been loaded properly, an error message "soundFormats is not defined" comes up.