switch(mode) {
case 0:
if (millis() - timer >= 100) {
file.play();
timer = millis();
}
break;
case 1:
if (millis() - timer >= 1000) {
file1.play();
timer = millis();
}
break;
}
我想创建一个基于时间的程序,如交通信号灯。 它将播放声音并持续3秒。 3秒后,它会变成另一种声音并持续10秒.10秒后,它将变为第一声。等等。我如何计算两个案件的时间?
答案 0 :(得分:0)
用于比较millis()
和timer
在逻辑方面的外观的条件。您可能希望将值更改为3秒和10秒(而不是0.1秒和1秒)
感觉你只需要3种状态:
播放声音并持续3秒。
3秒后,它会变成另一种声音并持续10秒
10秒后,它将变为第一声。
这样的事情:
int mode;
int timer;
void setup() {
println("starting in 1st mode, seconds:",second());
}
void draw() {
switch(mode) {
case 0:
if (millis() - timer >= 3000) {
println("play sound 1, seconds:",second());
timer = millis();
mode = 1;//change to the state to the next one
}
break;
case 1:
if (millis() - timer >= 3000) {
print("play sound 2, seconds:",second());
timer = millis();
mode = 2;//go to next mode
}
break;
case 2:
if (millis() - timer >= 10000) {//wait 10s
println("\n10s passed, going to 1st mode, seconds:",second());
timer = millis();
mode = 0;//go to next mode, after 10s
}
break;
}
}
就时间而言,你应该让状态以3s,3s和10s的增量循环。
如果声音按照预期发挥,我不是100%,但首先用一些println()
命令测试,看看在你预期的时间发生了什么状态,然后简单地触发你需要的声音正确的地方。
演示时间:
var mode = 0;
var timer;
function setup() {
createCanvas(100,100);
timer = millis()
console.log("starting in 1st mode, seconds:",second());
}
function draw() {
background(255);
text("mode: " + mode + "\nseconds: " + second(),10,10);
switch(mode) {
case 0:
if (millis() - timer >= 3000) {
console.log("play sound 1, seconds:",second());
timer = millis();
mode = 1;//change to the state to the next one
}
break;
case 1:
if (millis() - timer >= 3000) {
console.log("play sound 2, seconds:",second());
timer = millis();
mode = 2;//go to next mode
}
break;
case 2:
if (millis() - timer >= 10000) {//wait 10s
console.log("10s passed, going to 1st mode, seconds:",second());
timer = millis();
mode = 0;//go to next mode, after 10s
}
break;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.5/p5.min.js"></script>