Include functions in multiple projects

Hey, I’ve looked around a bit whether my questions was asked before, but I couldn’t see it … so …

I’ve written some functions of my own which I’d like to use in multiple projects. So, I save those functions to a dedicated file MyFuncs.rb. Now I’m trying to include or load that fie.

Sounds easy, but how to do that?

  • using load_buffer /path/to/MyFuncs.rb -> this will completely replace the current buffer - not what I want.
  • using Ruby’s native load or require -> this will lead to error "undefined method define". I guess the included file does not know about the SonicPi system and its functions.
  • In one project, it says "GUI Error: buffer full … use load_file", but also there’s no such function load_file. So how can I break things up properly?

One way is to use

run_file [path_to_file]

If you want the code to be available for all of your projects the more conveniant way is to add it to your SP startup file. Under Linux mine can be found at:

/home/[username]/.sonic-pi/init.rb

In my case it contains e. g.:

# Sonic Pi init file
# Code in here will be evaluated on launch.

load_snippets("~/.sonic-pi/snippets")

# to referenced e. g. like: 'sample atmos, 0'
define :atmos do
  atmos = "/path/to/some/sample/libraries/"
end

# more libraries

#################################################
# Custom functions ##############################
#################################################

# https://github.com/samaaron/sonic-pi/issues/1691
# modified by mb@mkblog.org
# Use: midi_chord chord(:c4, :major), sustain: 0.2
define :midi_chord do |notes, *args|
  if notes != :r
    notes.each do |note|
      midi note, *args
    end
  else
    play :r
  end
end

Hope this helps.

Martin

2 Likes

Thanks Martin, that’s what I needed! :slight_smile:

Just a remark. I am working still on my LiveLooper project (incorporating the Arturia BeatStep, which is a nifty device). I had some strange latencies, which matter, because I am recording live and need to play back these samples in time.

I observed, if I put all code in the main buffer (without using the run_file command) I do not have these latencies or at least very much reduced and correctable with time_warp. This might be due to poor code (or code organisation) but if you encounter a similar issue I’d be gratefull to hear about it.

Martin