Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

Drum loops

edited September 28 in Questions Posts: 19

I am trying to create a drum loop.
So I have to be able to set the time between beats. I have attempted to set a time of 1 second between loops.
Here is my code

function setup()
— t1 = Elapsed Time
—t2 = ElapsedTime
—I was wondering if these needed to be defined as global.. It made no difference.
end

function draw()

background(40, 40, 50)
strokeWidth(5)

rect(WIDTH/2-100,HEIGHT/2-50,200,100)

end

function touched(t)
if t.state == BEGAN and t.x>WIDTH/2-100 and t.x<WIDTH/2+100 and t.y>HEIGHT/2-50 and t.y<HEIGHT/2+50 then

    DrumLoop()
end

end

function DrumLoop()
t1 = ElapsedTime
--t1 = os.time()
sound(asset.documents.MySounds.Honey_Bucket_Mid)

repeat
t2=ElapsedTime
--until os.difftime(t2-t1)>1
until (t2-t1)>1
sound(asset.documents.MySounds.Honey_Bucket_Mid)

end

The “repeat until loop” doesn’t work. If I use t2 - t1 the first beat is played then the code goes into a continual loop not getting to the second beat (or sound)
If I use os.difftime I get an error. Something like expecting a numerical value for the second argument in difftime.

I have also tried this with os.clock and os.time

I must be doing something wrong.

Comments

  • dave1707dave1707 Mod
    edited September 28 Posts: 8,622

    @congokjt A lot of build in variables don’t get updated again until you exit the function they’re used in. So in the function DrumLoop(), the variable t1 will get the value from ElapsedTime. The variable t2 will have the same value as t1 because ElapsedTime won’t be updated again until you exit DrumLoop(). Codea can’t update the variable if you’re in a loop and don’t exit the function. So what you’re doing won’t work. You’ll have to come up with a different way you’re doing that. You could add more variables so when you play the first sound, you don’t play the second sound until you set a second variable.

  • dave1707dave1707 Mod
    Posts: 8,622

    Here’s an example to show what’s happening. Tap the button to start DrumLoop which will loop for several seconds. It prints the ElapsedTime value before and after the loop. They’ll be the same. Tap again to see an updated ElapsedTime.

    function setup()
    end
    
    function draw()    
        background(40, 40, 50)
        strokeWidth(5)    
        rect(WIDTH/2-100,HEIGHT/2-50,200,100)
    end
    
    function touched(t)
        if t.state == BEGAN and t.x>WIDTH/2-100 and t.x<WIDTH/2+100 and 
                t.y>HEIGHT/2-50 and t.y<HEIGHT/2+50 then        
            DrumLoop()
        end
    end
    
    function DrumLoop()
        print("start drumloop")
        t1=ElapsedTime
        print(t1)
        for z=1,100000000 do
            a=math.sqrt(z)
        end
        print("end drumloop")
        t1=ElapsedTime
        print(t1)
    end
    
Sign In or Register to comment.