Trigger sample halfway through the first one question

Another question :slight_smile: I wanted to trigger the amen break on the left and then halfway through I wanted trigger the sample again on the right. I typed the codes as follows but it didn’t work as intended. It plays the amen break once on the centre and there is no error message telling me where I was wrong…Could you let me know where I did wrong,? Thanks again :slight_smile:

sample :loop_amen, pan: -1
sleep (1/2) * (sample_duration(:loop_amen))
sample :loop_amen, pan: 1 

Something to keep in mind is that Ruby (the language that Sonic Pi is built on) makes certain assumptions about numbers when you use the division operator (/).

If you divide between two integers, then it will treat the result also as an integer (ie ignore any fractional part after the decimal point).

This means that in your above example, (1/2) actually results in 0 - so your script plays both samples at exactly the same time, one in the left channel, one in the right.

instead, you want to tell Sonic Pi/Ruby that you want to keep the fractional number, by treating the division result as a floating point number. You can do this by making sure at least one of the numbers in the division is itself a floating point number - for example, by using (1.0/2). That will give you the desired result of 0.5 :slightly_smiling_face:


Thanks a lot for this. Again of course, it worked. I am 50 and never coded before, so I would never have known about this. Maybe it’s time for me to pick up a Ruby book for my old brain. LOL. :grin: I might have more questions as I read through the tutorials and experiment the codes, hope you don’t mind…I am a guitarist and wanted to get involved in coding music for doing back track. Again thanks a bunch.

1 Like

No problem at all! Have fun exploring. Feel free to share any experiments if you’re comfortable doing so :slight_smile: