在 p5.js 中使用 for 循环索引音符仅播放单个音符。尽管有 setTimeout,但仍会执行 for 循环。不会按预期播放
希望运行 for 循环索引音符。运行 forloop 而不按预期演奏音符。花了几天时间阅读文档、堆栈溢出、youtube 编码训练,但仍然无法使其按预期工作,请帮忙
let notes=["A4","B4","C4","D4"]
function setup() {
monoSynth = new p5.MonoSynth();
setTimeout(playStuff,1000)
}
function playStuff(){
let i=0
for (i=0;i<notes.length;i++){
monoSynth.play(notes[i], 5, 3, 1 / 6);
print(i)
}//for i
}//playStuff
function draw() {
playStuff()
noLoop()
}//draw
wish to run a for loop indexing musical notes. runs through forloop without playing notes as expected. have spent a few days reading docs, stack overflow, youtube coding train and still cannot get it to work as expected please help
let notes=["A4","B4","C4","D4"]
function setup() {
monoSynth = new p5.MonoSynth();
setTimeout(playStuff,1000)
}
function playStuff(){
let i=0
for (i=0;i<notes.length;i++){
monoSynth.play(notes[i], 5, 3, 1 / 6);
print(i)
}//for i
}//playStuff
function draw() {
playStuff()
noLoop()
}//draw
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
setTimeout
函数仅控制何时调用playStuff()
函数,从而控制何时开始演奏音符。一旦调用playStuff()
函数,它将与浏览器一样快地执行。重要的是:p5.MonoSynth.play()
不会阻塞直到播放完毕。它只是安排要播放的音符并立即返回。有两种方法可以实现所需的计时: 1) 使用带有延迟的 async/away 为 for 循环添加时间延迟; 2) 让playStuff
接受索引参数并仅播放单个音符,但安排其自身稍后使用setTimeout
再次调用。我打算建议第三个选项:利用 p5.MonoSynth.play() 的第三个参数,这是从现在开始播放音符的时间。然而,您似乎只能安排一个未开始的笔记。就我个人而言,我喜欢选项#1,因为它不会实质性地改变代码的结构。然而,它确实有一个缺点,即需要对 JavaScript 中的异步编程有一定的了解。
注意:这些代码片段不会产生任何音频,因为 StackOverflow 会阻止 Stack Snippet iframe 中的音频
The
setTimeout
function is only going to control when theplayStuff()
function is called, and thus when you start playing notes. Once theplayStuff()
function is called it will execute as fast as the browser can. Importantly:p5.MonoSynth.play()
does not block until the not finishes playing. It simply schedules the note to be played and returns immediately. There are two ways you can achieve the desired timing: 1) Use async/away with a delay to add a time delay to your for loop; 2) HaveplayStuff
take an index argument and only play a single note, but schedule itself to be called again later usingsetTimeout
. I was going to suggest a third option: utilize the third parameter ofp5.MonoSynth.play()
which is the time from the present when the note should be played. However it seems that you can have only a single un-started note scheduled.Personally I like option #1 because it doesn't substantially change the structure of the code. However it does have the downside of requiring some understanding of asynchronous programming in JavaScript.
Note: These snippets will not produce any audio, because StackOverflow blocks audio in Stack Snippet iframes ????
Option #2
该演示将使用计时器每秒在数组中播放一次音符。如果你想让它重复循环,删除 noLoop() 并插入 counter = 0;
This demo will play a note every second, one time through the array, using a timer. If you want it to loop repeatedly, delete the noLoop() and insert counter = 0;