Search code examples
clojureovertone

How to play a note using a custom sample in overtone?


How can one play a note in overtone using a custom sample?

For example, you can play a note using predefined piano sample like (piano (note :C4)) but how can I do the same for custom sample that I loaded using sample or load-sample?

In other words: let's say I have (def my-piano (load-sample "/path/to/my/piano_sample.wav")) and want to use it instead of predefined piano instrument.

My understanding is that I need to define a new instrument that takes either note or frequency as an argument. The question is how to define such instrument. Neither scaled-play-buf nor play-buf don't take frequency as a parameter.

I've seen an example - 'how to define a custom instrument in overtone' here - and it looks like that I should have a separate sample per note. Is that correct?


Solution

  • Found an answer (sort of) - :rate parameter in scaled-play-buf can be used to achieve the desired effect (well, it's better used in combination with others actually, esp. if you want to play multiple octaves with your instrument):

    ;; define sample and instrument, rate is the key here
    (def piano (sample "~/Music/Samples/mypiano.wav"))
    (definst i-piano
                    [note 60 level 1 rate 1 loop? 0 attack 0 decay 1 sustain 1 release 0.1 curve -4 gate 1]
                    (let [env (env-gen (adsr attack decay sustain release level curve)
                                :gate gate
                                :action FREE)]
                      (scaled-play-buf 1 piano :rate rate :level level :loop loop? :action FREE)))
    
    ;; try it
    (i-piano :rate 1) ; original note
    (i-piano :rate 1.2)
    (i-piano :rate 0.7)