setup() が呼び出される前にサウンドが完全に読み込まれるようにするには、preload() 中に loadSound() を呼び出します。ローカルで実行するには、p5.soundライブラリ、サウンドファイル、およびローカルサーバーが必要です。
preload loadSound sound
Sound Structure
View Source Code
/*
* @name Preload SoundFile
* @arialabel On page load, a green screen plays music. When the user clicks on it, the screen turns red and stops playing music
* @description Call loadSound() during preload() to ensure that the
* sound is completely loaded before setup() is called. It's best to always
* call loadSound() in preload(), otherwise sounds won't necessarily be loaded
* by the time you want to play them in your sketch.
*
* <br><br><em><span class="small"> To run this example locally, you will need the
* <a href="http://p5js.org/reference/#/libraries/p5.sound">p5.sound library</a>
* a sound file, and a running <a href="https://github.com/processing/p5.js/wiki/Local-server">local server</a>.</span></em>
*/
let song;
function preload() {
// song = loadSound('assets/lucky_dragons_-_power_melody.mp3');
song = loadSound('../../../../p5js-website-legacy-examples/assets/lucky_dragons_-_power_melody.mp3');
}
function setup() {
// createCanvas(710, 200);
createCanvas(windowWidth, windowHeight);
song.loop(); // song is ready to play during setup() because it was loaded during preload
background(0, 255, 0);
}
function mousePressed() {
if (song.isPlaying()) {
// .isPlaying() returns a boolean
song.pause(); // .play() will resume from .pause() position
background(255, 0, 0);
} else {
song.play();
background(0, 255, 0);
}
}
License
Source code is available on GitHub p5.js website legacy.
All examples are licensed under CC BY-NC-SA 4.0.