# [chuck-users] Looping

Michael Heuer heuermh at gmail.com
Tue Sep 25 17:37:16 EDT 2012

```Alberto Alassio wrote:

> but what if I want to do this with 2 sines?
>
> I mean, for example
>
> Sineosc s1 that sounds and stop the same freq every 2 second, and another
> Sineosc thats sound at the same freq every 1 second I can use while true and
> put everthing in the bracklets. Right? Is it possible to do the same thing
> also with the For structure you mentioned?
>
> And what about
>
> sineosc s1  at 220 hz that goes on and off every 2 seconds
> sineosc s2 that has a random frequency ( std.rand2f for example )
> How could I manage this situation with while?  I need while ( true ) to make
> it in an infinite loop but I also need to make the random freq goes on!

If you do this

SinOsc s1 => dac;
220.0 => s1.freq;
for (0 => int i; i < 10; i++)
{
0.2 => s1.gain;
2::second => now;
0.0 => s1.gain;
2::second => now;
}

SinOsc s2 => dac;
for (0 => int i; i < 10; i++)
{
Std.rand2f(130.0, 440.0) => s2.freq;
0.2 => s2.gain;
2::second => now;
0.0 => s2.gain;
2::second => now;
}

then s2 will follow s1.

If you want them to go simultaneously, then you'll need to put one or
both loops in a function and spork the function call, for example

SinOsc s1 => dac;
220.0 => s1.freq;
spork ~ loop1();

SinOsc s2 => dac;
spork ~ loop2();

<<<"waiting on main shred">>>;
2::minute => now;

fun void loop1()
{
<<<"sporked loop1">>>;
for (0 => int i; i < 10; i++)
{
0.2 => s1.gain;
2::second => now;
0.0 => s1.gain;
2::second => now;
}
<<<"loop1 done">>>;
}

fun void loop2()
{
<<<"sporked loop2">>>;
for (0 => int i; i < 10; i++)
{
Std.rand2f(130.0, 440.0) => s2.freq;
0.2 => s2.gain;
2::second => now;
0.0 => s2.gain;
2::second => now;
}
<<<"loop2 done">>>;
}

michael
```