How to truncate a loop

Hi folks, fairly new to Sonic Pi. I have been trying to sort this out for the whole day. I have a loop with know BPM but it’s more than 4 bars and less than 5 bars. I want it to loop very 4 bars, so I set sleep as 16 so. that works. The issues is that when the loop starts again, the 5th bar of the previous loop still ring out. I try to use finish function but I don’t exactly where to finish since I don’t really know the length in time how long the loop is and what length would be for only the first 4 bars. so I can’t really calculate the ratio. How do you folks handle situations like this? Thank you,

Hello @quekou!

Seeing your code might make it easier to work out a potential solution for you - any chance you can show us?

As a rough starting idea, is keeping track of which iteration through the loop you are in so that you can potentially do something different that time around, useful at all?

live_loop :test do
  use_bpm 70
  GuitarRiff1 =  "/Users/macos/Library/Mobile Documents/com~apple~CloudDocs/Guitar Books/Riffs/The hunger/0005 2022_01_14 23_24_11 E 70bpm.wav"
  sample GuitarRiff1
  sleep 16

Thanks, The GuitarRiff1 is between 4 bars and 5 bars long. It’s bpm is 70. The above code will start he riff at the right start point but the issue is that the section after bar 4 still gets played after the loop has gone around staring at bar 1. so how am I supposed to make sure the loop only goes up to the end of bar 4 when it starts to loop itself from bar 1.
Thanks very much

I see. So is the issue here that you only ever want to play part of the sample, and ignore the last little bit of it? Then yes, using the finish: opt is possibly the easiest way to do this - if you are not sure at what point to stop playing, you can find this by using a calculation like the following:

sample GuitarRiff1, finish: (16.0 / sample_duration(GuitarRiff1))

(Since we know that in 4/4 timing, 16 beats is 4 bars, and sample_duration gives the length of the whole sample in beats).

Does that suit your needs? :slight_smile:

(Btw, to get nice code highlighting and indentation, you can put a blank line before and after your code examples here, and on these blank lines, put three backticks ``` - it makes code examples nice and easy to read :slightly_smiling_face: (I took the liberty of formatting your code example above to show this).

1 Like

wow, it worked. Thanks very much. I need to get myself familiar with more functions…and thanks for the tip on the formatting as well Cheers.

1 Like

You’re welcome, always happy to help where I can :+1: