【发布时间】:2022-12-25 03:42:45
【问题描述】:
https://editor.p5js.org/hvgrajciar/full/KIOn1sX6h
我在让这些音频文件与我的音板贴图一起使用时遇到问题。我想将每个音频文件附加到地图上相应的按钮,但每次我加载另一个音频文件时,它都会弄乱其他音频文件和它们所附加的按钮。
例如,我将在预加载中加载第二个音频文件后按下第一个音频按钮,第一个音频按钮将开始播放第二个音频文件而不是第一个。即使我已尽力将按钮声明为变量,这些变量附加到将在按下按钮时播放正确音频文件的函数,也会发生这种情况。
这是我与 p5js 的第一个任务,我觉得我真的很接近,但我错过了一些重要的东西。
var scotland;
let mySound;
var button1;
var button2;
var button3;
var button4;
var button5;
var button6;
function preload() {
scotland = createImg("https://i.redd.it/czyk6caeln921.png");
mySound = loadSound("audio/1clip.ogg");
mySound2 = loadSound("audio/2clip.mp3");
mySound3 = loadSound("audio/3clip.mp3");
mySound4 = loadSound("audio/4clip.mp3");
}
function setup() {
createCanvas(700, 900);
button1 = createButton("Shetland");
button1.position(600, 100);
button2 = createButton("Glasgow");
button2.position(320, 730);
button3 = createButton("Aberdeen");
button3.position(540, 520);
button4 = createButton("Isle of Lewis");
button4.position(200, 380);
button5 = createButton("The Scottish Borders");
button5.position(400, 800);
button6 = createButton("Argyll");
button6.position(290, 620);
button7 = createButton("Ross Sutherland");
button7.position(320, 400);
// Header Text for Map
var div = createDiv("");
div.html("Scottish Regions and Accents");
div.position(60, 80);
div.style("font-size", "32px");
div.style("textStyle", "Impact");
}
function mousePressed(button1) {
if (mySound.isPlaying()) {
// .isPlaying() returns a boolean
mySound.stop();
} else {
mySound.play();
}
}
function mousePressed(button2) {
if (mySound2.isPlaying()) {
// .isPlaying() returns a boolean
song.stop();
} else {
mySound2.play();
}
}
function mousePressed(button3) {
if (mySound3.isPlaying()) {
// .isPlaying() returns a boolean
mySound3.stop();
} else {
mySound3.play();
}
}
function mousePressed(button4) {
if (mySound4.isPlaying()) {
// .isPlaying() returns a boolean
mySound4.stop();
} else {
mySound4.play();
}
}
function draw() {
background(220);
scotland.position(0, 0);
scotland.size(700, 950);
}
【问题讨论】:
-
您可能想查看数组和循环。
-
谢谢你给我一些建议,帮助我朝着正确的方向前进。
-
function mousePressed(button4) {并没有按照您的想法去做——mousePressed函数被一遍又一遍地重新声明,参数是未使用的变量,而不是告诉 p5 您要将处理程序添加到哪个按钮的东西,所以只有最后一个注册。它不特定于任何按钮。相反,它会在鼠标按下任何地方时触发。试试button1.mousePressed(() => {/* handle sound 1 changes */});。 -
您也有
song.stop();但您的代码中没有song变量。我建议您在工作时使用 prettier.io/playground 格式化您的代码——我为您做了第一个。
标签: javascript arrays button audio p5.js