Wowkster
Wowkster

Reputation: 195

How to play sounds in p5.js

I am trying to use sound files for new year's eve firework explosions in p5, but I keep getting these errors:

p5.sound.js:1883 Access to XMLHttpRequest at 'file:///C:/Users/adyow/Desktop/Fireworks/explosion.mp3' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
There was no response from the server at explosion.mp3. Check the url and internet connectivity.
 The error stack trace includes: 
loadSound
    at preload (file:///C:/Users/adyow/Desktop/Fireworks/sketch.js:18:17)
    at preload (file:///C:/Users/adyow/Desktop/Fireworks/sketch.js:18:17)
request.onerror @ p5.sound.js:1880
p5.SoundFile.load @ p5.sound.js:1883
p5.SoundFile @ p5.sound.js:1748
p5.loadSound @ p5.sound.js:1803
(anonymous) @ p5.min.js:3
preload @ sketch.js:18
_start @ p5.min.js:3
b @ p5.min.js:3
n @ p5.min.js:3
error (async)
p5.SoundFile.load @ p5.sound.js:1873
p5.SoundFile @ p5.sound.js:1748
p5.loadSound @ p5.sound.js:1803
(anonymous) @ p5.min.js:3
preload @ sketch.js:18
_start @ p5.min.js:3
b @ p5.min.js:3
n @ p5.min.js:3
load (async)
24.../core/main @ p5.min.js:3
u @ p5.min.js:3
(anonymous) @ p5.min.js:3
15../color/color_conversion @ p5.min.js:3
u @ p5.min.js:3
n @ p5.min.js:3
(anonymous) @ p5.min.js:3
(anonymous) @ p5.min.js:3
(anonymous) @ p5.min.js:3

I used the example from https://p5js.org/examples/sound-sound-effect.html and just changed the file names, but I can't get it to work. I have done some googling but can't find a good answer.

Here is my index.html:

<html>

<head>
        <meta charset="UTF-8">
        <script language="javascript" type="text/javascript"
                src="https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.min.js"></script>

        <script language="javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/lib/addons/p5.sound.min.js"></script>
        <script language="javascript" type="text/javascript" src="particle.js"></script>
        <script language="javascript" type="text/javascript" src="firework.js"></script>
        <script language="javascript" type="text/javascript" src="sketch.js"></script>
        <script language="javascript" type="text/javascript" src="count.js"></script>
        <script language="javascript" type="text/javascript" src="p5.sound.js"></script>
        <style>
        body {
                background-color: black;
        }

        </style>

</head>

<body>
</body>

</html>

and here are my js files:

sketch.js

// Global Variable Declaration:

// create an empty array for the fireworks
var fireworks = [];
//create a global gravitational force
var gravity;
//set is New year to false
var isNewYear = false;
//set the date of new years
var deadline = "December 31 2019 21:46:00";
var explosion;
// --------------------------------------------------------------


function preload() {
    soundFormats('mp3', 'ogg');
    explosion = loadSound('explosion.mp3');
  }


//the setup function runs once on startup
function setup() {
    // create a canvas with a width of just under the browser's width and just under the browser's height
    createCanvas(innerWidth - 10, innerHeight - 20);
    //set the background to 0 (black)
    background(0);
    //set the global gravitational force as a vector object
    gravity = createVector(0, 0.2);

    // explosion.preload();
}

// --------------------------------------------------------------

//the draw function loops at 60 times a second
function draw() {

    //set the background to 0 (black) with some opacity to show the previous frame creating a trail effect
    background(0, 50);
    //loop through the fireworks array and update their location and show them on the screen
    for (var i = fireworks.length - 1; i >= 0; i--) {
        fireworks[i].update();
        fireworks[i].show();
        //if the firework is done remove it from the array (this makes the sketch run faster)
        if (fireworks[i].done()) {
            fireworks.splice(i, 1);
        }
    }

    // detect if it is New Year
    if (Math.floor(getTimeRemaining(deadline).total) <= 1) {
        // set is New Year to true
        isNewYear = true;
    }

    // if it is New Year, do this:
    if (isNewYear) {

        //if a random float between 0 and 1 is less than 0.2, add a new firework to the firworks array
        if (random(1) < 0.2) {
            fireworks.push(new Firework());
        }

        //display the text "Happy New Years!" and set the clock to 0
        displayText("Happy New Years!", "00:00:00", 72, 0, 0, 255, 255, 255, 255, 150, 250)
    }

    //if it's not new year, run this:
    else {
        if (Math.floor(getTimeRemaining(deadline).total) <= 60000) {
            //set the time left variable to a string with all of the different times seperated by a ":"
            var secLeft = getTimeRemaining(deadline).seconds;
            //display the text "New Years Eve Count Down" and show the timeLeft Variable as the clock
            displayText("New Years Eve Count Down", secLeft + " Seconds", 72, 255, 0, 255, 255, 255, 255, 150, 250);
        }

        else {
            //set the time left variable to a string with all of the different times seperated by a ":"
            var timeLeft = getTimeRemaining(deadline).hours + ":" + getTimeRemaining(deadline).minutes + ":" + getTimeRemaining(deadline).seconds;
            //display the text "New Years Eve Count Down" and show the timeLeft Variable as the clock
            displayText("New Years Eve Count Down", timeLeft, 64, 255, 0, 0, 255, 255, 255, 150, 250);
        }
    }
}

Particle.js:

function Particle(x, y, hu1,hu2, hu3, isFirework) {
    this.pos = createVector(x, y);
    this.isFirework = isFirework
    this.lifespan = 255;
    this.hu1 = hu1;
    this.hu2 = hu2;
    this.hu3 = hu3;

    if (this.isFirework) {
        this.vel = createVector(0, random(-18, -12));
    }
    else {
        this.vel = p5.Vector.random2D();
        this.vel.mult(random(1, 6));
    }
    this.acc = createVector(0, 0);

    this.applyForce = function (force) {
        this.acc.add(force);
    }

    this.update = function () {
        if (!this.isFirework) {
            this.vel.mult(0.99);
            this.lifespan -= 4

        }
        this.vel.add(this.acc);
        this.pos.add(this.vel);
        this.acc.mult(0);
    }

    this.show = function () {
        stroke(hu1, hu2, hu3, this.lifespan)
        // stroke(hu1, this.lifespan)
        strokeWeight(6)
        point(this.pos.x, this.pos.y);
    }
}

firework.js:

function Firework() {
    this.hu1 = random(255);
    this.hu2 = random(255);
    this.hu3 = random(255)
    this.firework = new Particle(random(width), height, this.hu1, this.hu2, this.hu3, true);
    this.exploded = false;
    this.particles = [];


    this.update = function () {
        if (!this.exploded) {
            this.firework.applyForce(gravity);
            this.firework.update();
            this.firework.show();
            if (this.firework.vel.y >= 0) {
                this.exploded = true;
                this.explode();
            }
        }


        for (var i = this.particles.length - 1; i >= 0; i--) {
            this.particles[i].applyForce(gravity);
            this.particles[i].update();
            if (this.particles[i].lifespan <= 0) {
                this.particles.splice(i, 1);
            }
        }

    }

    this.done = function () {
        if (this.exploded && this.particles.length === 0) {
            return true;
        }
        else {
            return false;
        }
    }

    this.explode = function () {
        explosion.play();
        for (var i = 0; i < 100; i++) {
            var p = new Particle(this.firework.pos.x, this.firework.pos.y, this.hu1, this.hu2, this.hu3, false);
            this.particles.push(p);
        }
    }

    this.show = function () {
        if (!this.exploded) {
            this.firework.show();
        }

        for (var i = 0; i < this.particles.length; i++) {
            this.particles[i].show();
        }

    }

}

and count.js

function getTimeRemaining(endtime) {
    var t = Date.parse(endtime) - Date.parse(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));
    if (seconds < 10) {
        seconds = "0" + seconds
    }
    if (minutes < 10) {
        minutes = "0" + minutes
    }
    if (hours < 10) {
        hours = "0" + hours
    }
    return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };
}

function displayText(message, message2, txtSize, Stroke1, Stroke2, Stroke3, Fill1, Fill2, Fill3, y1, y2) {

    textSize(txtSize);
    stroke(Stroke1, Stroke2, Stroke3);
    strokeWeight(3);
    fill(Fill1, Fill2, Fill3);
    textAlign(CENTER);
    text(message, width / 2, y1);
    text(message2, width / 2, y2);

}

Upvotes: 0

Views: 2847

Answers (1)

Carter
Carter

Reputation: 1

This is easy to fix, I've ran into it before.

It means file:// is origin "null" and so a file tries to access another file, AKA origin null trying to access origin null, and it produces an error.

There is two ways to fix this:

  1. Run chrome using the --disable-web-security option and changing the --user-data-dir to something like /tmp/dev session/

or

  1. Use a lightweight server like apache to host your p5 script on your localhost which can be accessed at localhost:80 or localhost:8080.

Upvotes: 0

Related Questions