Hi,
You could either load all samples into memory to begin with, or stream them from disk (which saves memory in case you have a lot of samples). Here is an example of streaming from disk:
( // 1. prep
// folder with samples
~folderpath = "/path/to/your/folder/";
~files = PathName(~folderpath).files;
s.waitForBoot {
SynthDef(\playFile, { |out, buf|
Out.ar(out, DiskIn.ar(2, buf).poll);
}).add;
~buffer = Buffer.alloc(s, 32768, 2); // assuming stereo files
};
)
( // 2. pick a random file and play it
var file = ~files.choose;
fork {
~buffer.close;
~buffer.cueSoundFile(file.fullPath, 0);
s.sync;
Synth(\playFile, [buf: ~buffer]);
}
)
For me this works with .mp3 files as well as .wav which was a surprise to me! The last time I tried to work with .mp3 files (many years ago) I remember having to use the MP3 quark.
And to make this happen when you press a GUI button, use its action:
(
~window = Window().front;
~button = Button(~window, Rect(10, 10, 50, 30)).string_("Play").action_({
var file = ~files.choose;
fork {
~buffer.close;
~buffer.cueSoundFile(file.fullPath, 0);
s.sync;
Synth(\playFile, [buf: ~buffer]);
};
});
)