Hi guys, trying to simply play a sound in p5js but code doesn't work?

Hi, so basically the code below doesn’t work, I don’t know if it’s the file path, but it cannot load the sound for some reason. Error: There was no response from the server at C:UserslauriDownloadsInput.mp3. Check the url and internet connectivity.
The error stack trace includes: setup@about:srcdoc:83:13

Here is the code:

// The video
let video;
// For displaying the label
let label = "waiting...";
// The classifier
let classifier;
let modelURL = 'https://teachablemachine.withgoogle.com/models/e9uoLktk7/';

// STEP 1: Load the model!
function preload() {
  classifier = ml5.imageClassifier(modelURL + 'model.json');
}

function setup() {
  createCanvas(640, 520);
  // Create the video
  video = createCapture(VIDEO);
  video.hide();
  let mySound;
  soundFormats('mp3', 'ogg');
  mySound = loadSound("C:\Users\lauri\Downloads\Input.mp3");

  // STEP 2: Start classifying
  classifyVideo();
}

// STEP 2 classify the videeo!
function classifyVideo() {
  classifier.classify(video, gotResults);
}

function draw() {
  background(0);

  // Draw the video
  image(video, 0, 0);

  // STEP 4: Draw the label
  textSize(32);
  textAlign(CENTER, CENTER);
  fill(255);
  text(label, width / 2, height - 16);








}

// STEP 3: Get the classification!
function gotResults(error, results) {

  if (error) {
    console.error(error);
    return;
  }
  // Store the label and classify again!
  label = results[0].label;
  classifyVideo();
}

if (label == "Distracted") {
   mySound.play();
}

1 Like

Hello @llcoolj,

Websites can’t reference local files the way you are doing with loadSound("C:\Users\lauri\Downloads\Input.mp3");. And that is a good thing, a security feature. You wouldn’t want every website you visit to be able to read all your local files.

The mp3 has to exist alongside your HTML and JavaScript source code on the webserver. Where are you hosting this sketch – https://editor.p5js.org?

3 Likes

Hi Sven,

Thanks for the quick response. That makes a lot of sense. You are correct I am hosting it on the web server/editor:
https://editor.p5js.org

I already tried to upload it, since you can add files but mp3 is not supported. How do you think I can access it, online many people use the loadSound code, but then a different source code often containing assets/…"

Any ideas?

1 Like

I have good news; there is support for uploading mp3. :partying_face: But you have to create an account and login to see Upload file in the drop-down menu.

The thing with assets/… is just a convention. People like to put their assets (images, sounds, videos) inside a folder. Take a look at the screenshot below, where I have:

  1. Created a folder named assets.
  2. Uploaded Input.mp3 to that folder.
  3. Changed the code accordingly, to match the location of the file.

Do the above, and you should be on your way. :slight_smile:

2 Likes