首页 > 解决方案 > 如何在 p5.js 中播放声音

问题描述

我正在尝试将声音文件用于 p5 中的除夕烟花爆炸,但我不断收到以下错误:

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

我使用了https://p5js.org/examples/sound-sound-effect.html中的示例,只是更改了文件名,但我无法让它工作。我做了一些谷歌搜索,但找不到一个好的答案。

这是我的 index.html:

<html>

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

        <script language="javascript" src="https://cdn.jsdelivr.net/npm/p5@0.10.2/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>

这是我的js文件:

草图.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);
        }
    }
}

粒子.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();
        }

    }

}

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

}

标签: javascripthtmlaudiop5.jsfireworks

解决方案


这很容易解决,我以前遇到过。

这意味着 file:// 是原始“null”,因此文件尝试访问另一个文件,AKA origin null 尝试访问原始 null,它会产生错误。

有两种方法可以解决此问题:

  1. 使用 --disable-web-security 选项运行 chrome 并将 --user-data-dir 更改为 /tmp/dev session/

或者

  1. 使用像 apache 这样的轻量级服务器在 localhost 上托管 p5 脚本,可以在 localhost:80 或 localhost:8080 访问。

推荐阅读