rsc3/doc-schelp/HelpSource/Classes/Buffer.schelp

944 lines
44 KiB
Text
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class:: Buffer
summary:: Client-side representation of a buffer on a server
categories:: Server>Abstractions
description::
A buffer is most often used to hold sampled audio, such as a soundfile loaded into memory, but can be used to hold other types of data as well. It is a globally available array of floating-point numbers on the server. The Buffer class encapsulates a number of common tasks, OSC messages, and capabilities related to server-side buffers see the examples lower down this document for many examples of using Buffers for sound playback and recording.
Buffers are commonly used with link::Classes/PlayBuf::, link::Classes/RecordBuf::, link::Classes/DiskIn::, link::Classes/DiskOut::, link::Classes/BufWr::, link::Classes/BufRd::, and other UGens. (See their individual help files for more examples.) Buffers can be freed or altered even while being accessed. See link::Reference/Server-Architecture:: for some technical details.
Buffer objects should not be created or modified within a link::Classes/SynthDef::. If this is needed, see link::Classes/LocalBuf::.
subsection:: Buffer Numbers and Allocation
Although the number of buffers on a server is set at the time it is booted, memory must still be allocated within the server app before they can hold values. (At boot time all buffers have a size of 0.)
link::Classes/Server::-side buffers are identified by number, starting from 0. When using Buffer objects, buffer numbers are automatically allocated from the Server's bufferAllocator, unless you explicitly supply one. When you call code::.free:: on a Buffer object it will release the buffer's memory on the server, and free the buffer number for future reallocation. See link::Classes/ServerOptions:: for details on setting the number of available buffers.
Normally you should not need to supply a buffer number. You should only do so if you are sure you know what you are doing. Similarly, in normal use you should not need to access the buffer number, since instances of Buffer can be used directly as link::Classes/UGen:: inputs or link::Classes/Synth:: args.
subsection:: Multichannel Buffers
Multichannel buffers interleave their data. Thus the actual number of available values when requesting or setting values by index using methods such as code::set, setn, get, getn::, etc., is equal to code::numFrames * numChannels::.
Indices start at 0 and go up to code::(numFrames * numChannels) - 1::.
In a two channel buffer for instance, index 0 will be the first value of the first channel, index 1 will be the first value of the second channel, index 2 will be the second value of the first channel, and so on.
In some cases it is simpler to use multiple single channel buffers instead of a single multichannel one.
subsection:: Completion Messages and Action Functions
Many buffer operations (such as reading and writing files) are asynchronous, meaning that they will take an arbitrary amount of time to complete. Asynchronous commands are passed to a background thread on the server so as not to steal CPU time from the audio synthesis thread.
Since they can last an arbitrary amount of time it is convenient to be able to specify something else that can be done immediately on completion.
The ability to do this is implemented in two ways in Buffer's various methods: completion messages and action functions.
A completion message is a second OSC command which is included in the message which is sent to the server. (See link::Guides/NodeMessaging:: for a discussion of OSC messages.)
The server will execute this immediately upon completing the first command.
An action function is a link::Classes/Function:: which will be evaluated when the client receives the appropriate reply from the server, indicating that the previous command is done.
Action functions are therefore inherently more flexible than completion messages, but slightly less efficient due to the small amount of added latency involved in message traffic. Action functions are passed the Buffer object as an argument when they are evaluated.
With Buffer methods that take a completion message, it is also possible to pass in a function that returns an OSC message. As in action functions this will be passed the Buffer as an argument.
It is important to understand however that this function will be evaluated after the Buffer object has been created (so that its bufnum and other details are accessible), but before the corresponding message is sent to the server.
subsection:: Bundling
Many of the methods below have two versions: a regular one which sends its corresponding message to the server immediately, and one which returns the message in an link::Classes/Array:: so that it can be added to a bundle.
It is also possible to capture the messages generated by the regular methods using Server's automated bundling capabilities.
See link::Classes/Server:: and link::Guides/Bundled-Messages:: for more details.
classmethods::
private:: initClass, initServerCache, clearServerCaches
subsection:: Creation with Immediate Memory Allocation
method:: alloc
Create and return a Buffer and immediately allocate the required memory on the server. The buffer's values will be initialised to 0.0.
argument:: server
The server on which to allocate the buffer. The default is the default Server.
argument:: numFrames
The number of frames to allocate. Actual memory use will correspond to numFrames * numChannels.
argument:: numChannels
The number of channels for the Buffer. The default is 1.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
argument:: bufnum
An explicitly specified buffer number. Generally this is not needed.
discussion::
code::
// Allocate 8 second stereo buffer
s.boot;
b = Buffer.alloc(s, s.sampleRate * 8.0, 2);
b.free;
::
method:: allocConsecutive
Allocates a range of consecutively-numbered buffers, for use with UGens like link::Classes/VOsc:: and link::Classes/VOsc3:: that require a contiguous block of buffers, and returns an array of corresponding Buffer objects.
argument:: numBufs
The number of consecutively indexed buffers to allocate.
argument:: server
The server on which to allocate the buffers. The default is the default Server.
argument:: numFrames
The number of frames to allocate in each buffer. Actual memory use will correspond to numFrames * numChannels.
argument:: numChannels
The number of channels for each buffer. The default is 1.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed each Buffer and its index in the array as arguments when evaluated.
argument:: bufnum
An explicitly specified buffer number for the initial buffer. Generally this is not needed.
discussion::
N.B. You must treat the array of Buffers as a group. Freeing them individually or reusing them can result in allocation errors. You should free all Buffers in the array at the same time by iterating over it with do.
code::
s.boot;
// allocate an array of Buffers and fill them with different harmonics
(
b = Buffer.allocConsecutive(8, s, 4096, 1, { |buf, i|
buf.sine1Msg((1..((i+1)*6)).reciprocal) // completion Messages
});
a = { VOsc.ar(SinOsc.kr(0.5, 0).range(b.first.bufnum + 0.1, b.last.bufnum - 0.1),
[440, 441], 0, 0.2) }.play;
)
a.free;
// iterate over the array and free it
b.do(_.free);
::
method:: read
Allocate a buffer and immediately read a soundfile into it. This method sends a query message as a completion message so that the Buffer's instance variables will be updated automatically.
argument:: server
The server on which to allocate the buffer.
argument:: path
A String representing the path of the soundfile to be read.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
argument:: bufnum
An explicitly specified buffer number. Generally this is not needed.
discussion::
N.B. You cannot rely on the buffer's instance variables being instantly updated, as there is a small amount of latency involved. action will be evaluated upon receipt of the reply to the query, so use this in cases where access to instance variables is needed.
code::
// read a soundfile
s.boot;
p = Platform.resourceDir +/+ "sounds/a11wlk01.wav";
b = Buffer.read(s, p);
// now play it
(
x = SynthDef(\help_Buffer, { arg out = 0, bufnum;
Out.ar( out,
PlayBuf.ar(1, bufnum, BufRateScale.kr(bufnum))
)
}).play(s,[\bufnum, b]);
)
x.free; b.free;
// with an action function
// note that the vars are not immediately up-to-date
(
b = Buffer.read(s, p, action: { arg buffer;
("After update:" + buffer.numFrames).postln;
x = { PlayBuf.ar(1, buffer, BufRateScale.kr(buffer)) }.play;
});
("Before update:" + b.numFrames).postln;
)
x.free; b.free;
::
method:: readChannel
As link::#*read:: above, but takes an link::Classes/Array:: of channel indices to read in, allowing one to read only the selected channels.
argument:: server
The server on which to allocate the buffer.
argument:: path
A String representing the path of the soundfile to be read.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: channels
An Array of channels to be read from the soundfile. Indices start from zero. These will be read in the order provided.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
argument:: bufnum
An explicitly specified buffer number. Generally this is not needed.
discussion::
code::
s.boot;
// first a standard read so we can see what's in the file
b = Buffer.read(s, Platform.resourceDir +/+ "sounds/SinedPink.aiff");
// Platform.resourceDir +/+ "sounds/SinedPink.aiff" contains SinOsc on left, PinkNoise on right
b.plot;
b.free;
// Now just the sine
b = Buffer.readChannel(s, Platform.resourceDir +/+ "sounds/SinedPink.aiff", channels: [0]);
b.plot;
b.free;
// Now just the pink noise
b = Buffer.readChannel(s, Platform.resourceDir +/+ "sounds/SinedPink.aiff", channels: [1]);
b.plot;
b.free;
// Now reverse channel order
b = Buffer.readChannel(s, Platform.resourceDir +/+ "sounds/SinedPink.aiff", channels: [1, 0]);
b.plot;
b.free;
::
method:: readNoUpdate
As link::#*read:: above, but without the automatic update of instance variables. Call code::updateInfo:: (see below) to update the vars.
argument:: server
The server on which to allocate the buffer.
argument:: path
A String representing the path of the soundfile to be read.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: bufnum
An explicitly specified buffer number. Generally this is not needed.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
code::
// with a completion message
s.boot;
(
SynthDef(\help_Buffer,{ arg out=0, bufnum;
Out.ar( out,
PlayBuf.ar(1,bufnum,BufRateScale.kr(bufnum))
)
}).add;
y = Synth.basicNew(\help_Buffer); // not sent yet
b = Buffer.readNoUpdate(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav",
completionMessage: { arg buffer;
// synth add its s_new msg to follow
// after the buffer read completes
y.newMsg(s,[\bufnum, buffer],\addToTail)
});
)
// note vars not accurate
b.numFrames; // nil
b.updateInfo;
b.numFrames; // 188893
// when done...
y.free;
b.free;
::
method:: cueSoundFile
Allocate a buffer and preload a soundfile for streaming in using link::Classes/DiskIn::.
argument:: server
The server on which to allocate the buffer.
argument:: path
A String representing the path of the soundfile to be read.
argument:: startFrame
The frame of the soundfile that DiskIn will start playing at.
argument:: numChannels
The number of channels in the soundfile.
argument:: bufferSize
This must be a multiple of (2 * the server's block size). 32768 is the default and is suitable for most cases.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
code::
s.boot;
(
SynthDef(\help_Buffer_cue,{ arg out=0,bufnum;
Out.ar(out,
DiskIn.ar( 1, bufnum )
)
}).add;
)
(
s.makeBundle(nil, {
b = Buffer.cueSoundFile(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav", 0, 1);
y = Synth(\help_Buffer_cue, [\bufnum, b], s);
});
)
b.free; y.free;
::
method:: loadCollection
Load a large collection into a buffer on the server. Returns a Buffer object.
argument:: server
The server on which to create the buffer.
argument:: collection
A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
argument:: numChannels
The number of channels that the buffer should have. Note that buffers interleave multichannel data. You are responsible for providing an interleaved collection if needed. Multi-dimensional arrays will not work.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
discussion::
This is accomplished through writing the collection to a SoundFile and loading it from there. For this reason this method will only work with a server on your local machine. For a remote server use code::sendCollection::, below. The file is automatically deleted after loading. This allows for larger collections than setn, below, and is in general the safest way to get a large collection into a buffer. The sample rate of the buffer will be the sample rate of the server on which it is created.
code::
s.boot;
(
a = FloatArray.fill(44100 * 5.0, {1.0.rand2}); // 5 seconds of noise
b = Buffer.loadCollection(s, a);
)
// test it
b.get(20000,{|msg| (msg == a[20000]).postln});
// play it
x = { PlayBuf.ar(1, b, BufRateScale.kr(b), loop: 0) * 0.5 }.play;
b.free; x.free;
// interleave a multi-dimensional array
(
l = Signal.sineFill(16384, Array.fill(200, {0}).add(1));
r = Array.fill(16384, {1.0.rand2});
m = [Array.newFrom(l), r]; // a multi-dimensional array
m = m.lace(32768); // interleave the two collections
b = Buffer.loadCollection(s, m, 2, {|buf|
x = { PlayBuf.ar(2, buf, BufRateScale.kr(buf), loop: 1) * 0.5 }.play;
});
)
b.plot;
x.free; b.free;
::
method:: sendCollection
Stream a large collection into a buffer on the server using multiple setn messages. Returns a Buffer object.
argument:: server
The server on which to create the buffer.
argument:: collection
A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
argument:: numChannels
The number of channels that the buffer should have. Note that buffers interleave multichannel data. You are responsible for providing an interleaved collection if needed. Multi-dimensional arrays will not work. See the example in link::#*loadCollection:: above, to see how to do this.
argument:: wait
An optional wait time between sending setn messages. In a high traffic situation it may be safer to set this to something above zero, which is the default.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
discussion::
This allows for larger collections than setn, below. This is not as safe as link::#*loadCollection:: above, but will work with servers on remote machines. The sample rate of the buffer will be the sample rate of the server on which it is created.
code::
s.boot;
(
a = Array.fill(2000000,{ rrand(0.0,1.0) }); // a LARGE collection
b = Buffer.sendCollection(s, a, 1, 0, {arg buf; "finished".postln;});
)
b.get(1999999, {|msg| (msg == a[1999999]).postln});
b.free;
::
method:: loadDialog
As link::#*read:: above, but gives you a load dialog window to browse for a file. Cocoa and SwingOSC compatible.
argument:: server
The server on which to allocate the buffer.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
argument:: bufnum
An explicitly specified buffer number. Generally this is not needed.
discussion::
code::
s.boot;
(
b = Buffer.loadDialog(s, action: { arg buffer;
x = { PlayBuf.ar(buffer.numChannels, buffer, BufRateScale.kr(buffer)) }.play;
});
)
x.free; b.free;
::
subsection:: Creation without Immediate Memory Allocation
method:: new
Create and return a new Buffer object, without immediately allocating the corresponding memory on the server. This combined with 'message' methods can be flexible with bundles.
argument:: server
The server on which to allocate the buffer. The default is the default Server.
argument:: numFrames
The number of frames to allocate. Actual memory use will correspond to numFrames * numChannels.
argument:: numChannels
The number of channels for the Buffer. The default is 1.
argument:: bufnum
An explicitly specified buffer number. Generally this is not needed.
discussion::
code::
s.boot;
b = Buffer.new(s, 44100 * 8.0, 2);
c = Buffer.new(s, 44100 * 4.0, 2);
b.query; // numFrames = 0
s.sendBundle(nil, b.allocMsg, c.allocMsg); // sent both at the same time
b.query; // now it's right
c.query;
b.free; c.free;
::
subsection:: Cached Buffers
To assist with automatic updates of buffer information (see code::updateInfo:: and code::read::), buffer objects are cached in a collection associated with the link::Classes/Server:: object hosting the buffers.
Freeing a buffer removes it from the cache; quitting the server clears all the cached buffers. (This also occurs if the server crashes unexpectedly.)
You may access cached buffers using the following methods.
It may be simpler to access them through the server object:
code::
myServer.cachedBufferAt(bufnum)
myServer.cachedBuffersDo(func)
b = Buffer.alloc(s, 2048, 1);
Buffer.cachedBufferAt(s, 0); // assuming b has bufnum 0
s.cachedBufferAt(0); // same result
s.cachedBuffersDo({ |buf| buf.postln });
::
method:: cachedBufferAt
Access a buffer by its number.
method:: cachedBuffersDo
Iterate over all cached buffers. The iteration is not in any order, but will touch all buffers.
InstanceMethods::
subsection:: Variables
The following variables have getter methods.
method:: server
Returns the Buffer's Server object.
method:: bufnum
Returns the buffer number of the corresponding server-side buffer. In normal use you should not need to access this value, since instances of Buffer can be used directly as UGen inputs or Synth args.
discussion::
code::
s.boot;
b = Buffer.alloc(s,44100 * 8.0,2);
b.bufnum.postln;
b.free;
::
method:: numFrames
Returns the number of sample frames in the corresponding server-side buffer. Note that multichannel buffers interleave their samples, so when dealing with indices in methods like get and getn, the actual number of available values is numFrames * numChannels.
method:: numChannels
Returns the number of channels in the corresponding server-side buffer.
method:: sampleRate
Returns the sample rate of the corresponding server-side buffer.
method:: path
Returns a string containing the path of a soundfile that has been loaded into the corresponding server-side buffer.
subsection:: Explicit allocation
These methods allocate the necessary memory on the server for a Buffer previously created with link::#*new::.
method:: alloc, allocMsg
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
code::
s.boot;
b = Buffer.new(s, 44100 * 8.0, 2);
b.query; // numFrames = 0
b.alloc;
b.query; // numFrames = 352800
b.free;
::
method:: allocRead, allocReadMsg
Read a soundfile into a buffer on the server for a Buffer previously created with link::#*new::. Note that this will not autoupdate instance variables. Call code::updateInfo:: in order to do this.
argument:: argpath
A String representing the path of the soundfile to be read.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
code::
s.boot;
b = Buffer.new(s);
b.allocRead(Platform.resourceDir +/+ "sounds/a11wlk01.wav");
x = { PlayBuf.ar(1, b, BufRateScale.kr(b), loop: 1) * 0.5 }.play;
x.free; b.free;
::
method:: allocReadChannel, allocReadChannelMsg
As link::#-allocRead:: above, but allows you to specify which channels to read.
argument:: argpath
A String representing the path of the soundfile to be read.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: channels
An Array of channels to be read from the soundfile. Indices start from zero. These will be read in the order provided.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
code::
s.boot;
b = Buffer.new(s);
// read only the first channel (a Sine wave) of a stereo file
b.allocReadChannel(Platform.resourceDir +/+ "sounds/SinedPink.aiff", channels: [0]);
x = { PlayBuf.ar(1, b, BufRateScale.kr(b), loop: 1) * 0.5 }.play;
x.free; b.free;
::
subsection:: Other methods
method:: read, readMsg
Read a soundfile into an already allocated buffer.
argument:: argpath
A String representing the path of the soundfile to be read.
argument:: fileStartFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: bufStartFrame
The index of the frame in the buffer at which to start reading. The default is 0, which is the beginning of the buffer.
argument:: leaveOpen
A boolean indicating whether or not the Buffer should be left 'open'. For use with DiskIn you will want this to be true, as the buffer will be used for streaming the soundfile in from disk. (For this the buffer must have been allocated with a multiple of (2 * synth block size).
A common number is 32768 frames. cueSoundFile below, provides a simpler way of doing this.) The default is false which is the correct value for all other cases.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
Note that if the number of frames in the file is greater than the number of frames in the buffer, it will be truncated. Note that readMsg will not auto-update instance variables. Call updateInfo in order to do this.
method:: readChannel, readChannelMsg
As link::#-read:: above, but allows you to specify which channels to read.
argument:: argpath
A String representing the path of the soundfile to be read.
argument:: fileStartFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: numFrames
The number of frames to read. The default is -1, which will read the whole file.
argument:: bufStartFrame
The index of the frame in the buffer at which to start reading. The default is 0, which is the beginning of the buffer.
argument:: leaveOpen
A boolean indicating whether or not the Buffer should be left 'open'. For use with DiskIn you will want this to be true, as the buffer will be used for streaming the soundfile in from disk. (For this the buffer must have been allocated with a multiple of (2 * synth block size).
A common number is 32768 frames. cueSoundFile below, provides a simpler way of doing this.) The default is false which is the correct value for all other cases.
argument:: channels
An Array of channels to be read from the soundfile. Indices start from zero. These will be read in the order provided. The number of channels requested must match this Buffer's numChannels.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
method:: cueSoundFile, cueSoundFileMsg
A convenience method to cue a soundfile into the buffer for use with a link::Classes/DiskIn::. The buffer must have been allocated with a multiple of (2 * the server's block size) frames. A common size is 32768 frames.
argument:: path
A String representing the path of the soundfile to be read.
argument:: startFrame
The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
discussion::
code::
s.boot;
//create with cueSoundFile class method
b = Buffer.cueSoundFile(s, Platform.resourceDir +/+ "sounds/a11wlk01-44_1.aiff", 0, 1);
x = { DiskIn.ar(1, b) }.play;
b.close; // must call close in between cueing
// now use like named instance method, but different arguments
b.cueSoundFile(Platform.resourceDir +/+ "sounds/a11wlk01-44_1.aiff");
// have to do all this to clean up properly!
x.free; b.close; b.free;
::
method:: write, writeMsg
Write the contents of the buffer to a file. See link::Classes/SoundFile:: for information on valid values for headerFormat and sampleFormat.
argument:: path
A String representing the path of the soundfile to be written.
If no path is given, Buffer writes into the default recording directory with a generic name.
argument:: headerFormat
A String.
argument:: sampleFormat
A String.
argument:: numFrames
The number of frames to write. The default is -1, which will write the whole buffer.
argument:: startFrame
The index of the frame in the buffer from which to start writing. The default is 0, which is the beginning of the buffer.
argument:: leaveOpen
A boolean indicating whether or not the Buffer should be left 'open'. For use with DiskOut you will want this to be true. The default is false which is the correct value for all other cases.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
method:: free, freeMsg
Release the buffer's memory on the server and return the bufferID back to the server's buffer number allocator for future reuse.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
method:: zero, zeroMsg
Sets all values in this buffer to 0.0.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
method:: set, setMsg
Set the value in the buffer at index to be equal to float. Additional pairs of indices and floats may be included in the same message.
discussion::
Note that multichannel buffers interleave their sample data, therefore the actual number of available values is equal to code::numFrames * numChannels::. Indices start at 0.
code::
s.boot;
b = Buffer.alloc(s, 4, 2);
b.set(0, 0.2, 1, 0.3, 7, 0.4); // set the values at indices 0, 1, and 7.
b.getn(0, 8, {|msg| msg.postln});
b.free;
::
method:: setn, setnMsg
Set a contiguous range of values in the buffer starting at the index startAt to be equal to the Array of floats or integers, values. The number of values set corresponds to the size of values. Additional pairs of starting indices and arrays of values may be included in the same message.
discussion::
Note that multichannel buffers interleave their sample data, therefore the actual number of available values is equal to code::numFrames * numChannels::. You are responsible for interleaving the data in values if needed. Multi-dimensional arrays will not work. Indices start at 0.
N.B. The maximum number of values that you can set with a single setn message is 1633 when the server is using UDP as its communication protocol. Use link::#-loadCollection:: and link::#-sendCollection:: to set larger ranges of values.
code::
s.boot;
b = Buffer.alloc(s,16);
b.setn(0, Array.fill(16, { rrand(0,1) }));
b.getn(0, b.numFrames, {|msg| msg.postln});
b.setn(0, [1, 2, 3], 4, [1, 2, 3]);
b.getn(0, b.numFrames, {|msg| msg.postln});
b.free;
::
method:: loadCollection
Load a large collection into this buffer. This is accomplished through writing the collection to a SoundFile and loading it from there. For this reason this method will only work with a server on your local machine. For a remote server use sendCollection, below. The file is automatically deleted after loading.
argument:: collection
A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
argument:: startFrame
The index of the frame at which to start loading the collection. The default is 0, which is the start of the buffer.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
discussion::
This allows for larger collections than setn, above, and is in general the safest way to get a large collection into a buffer. The sample rate of the buffer will be the sample rate of the server on which it was created.
The number of channels and frames will have been determined when the buffer was allocated. You are responsible for making sure that the size of collection is not greater than numFrames, and for interleaving any data if needed.
code::
s.boot;
(
v = Signal.sineFill(128, 1.0/[1,2,3,4,5,6]);
b = Buffer.alloc(s, 128);
)
(
b.loadCollection(v, action: {|buf|
x = { PlayBuf.ar(buf.numChannels, buf, BufRateScale.kr(buf), loop: 1)
* 0.2 }.play;
});
)
x.free; b.free;
// interleave a multi-dimensional array
(
l = Signal.sineFill(16384, Array.fill(200, {0}).add(1));
r = Array.fill(16384, {1.0.rand2});
m = [Array.newFrom(l), r]; // a multi-dimensional array
m = m.lace(32768); // interleave the two collections
b = Buffer.alloc(s, 16384, 2);
)
(
b.loadCollection(m, 0, {|buf|
x = { PlayBuf.ar(2, buf, BufRateScale.kr(buf), loop: 1) * 0.5 }.play;
});
)
b.plot;
x.free; b.free;
::
method:: sendCollection
Stream a large collection into this buffer using multiple setn messages.
argument:: collection
A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
argument:: startFrame
The index of the frame at which to start streaming in the collection. The default is 0, which is the start of the buffer.
argument:: wait
An optional wait time between sending setn messages. In a high traffic situation it may be safer to set this to something above zero, which is the default.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
discussion::
This allows for larger collections than setn. This is not as safe as loadCollection, above, but will work with servers on remote machines. The sample rate of the buffer will be the sample rate of the server on which it is created.
code::
s.boot;
(
a = Array.fill(2000000,{ rrand(0.0,1.0) });
b = Buffer.alloc(s, 2000000);
)
b = b.sendCollection(a, action: {arg buf; "finished".postln;});
b.get(1999999, {|msg| (msg == a[1999999]).postln});
b.free;
::
method:: get, getMsg
Send a message requesting the value in the buffer at index. action is a Function which will be passed the value as an argument and evaluated when a reply is received.
discussion::
code::
s.boot;
b = Buffer.alloc(s,16);
b.setn(0, Array.fill(16, { rrand(0.0, 1.0) }));
b.get(0, {|msg| msg.postln});
b.free;
::
method:: getn, getMsg
Send a message requesting the a contiguous range of values of size count starting from index. action is a Function which will be passed the values in an Array as an argument and evaluated when a reply is received. See setn above for an example.
discussion::
N.B. The maximum number of values that you can get with a single getn message is 1633 when the server is using UDP as its communication protocol. Use link::#-loadToFloatArray:: and link::#-getToFloatArray:: to get larger ranges of values.
method:: loadToFloatArray
Write the buffer to a file and then load it into a FloatArray.
argument:: index
The index in the buffer to begin writing from. The default is 0.
argument:: count
The number of values to write. The default is -1, which writes from index until the end of the buffer.
argument:: action
A Function which will be passed the resulting FloatArray as an argument and evaluated when loading is finished.
discussion::
This is safer than getToFloatArray but only works with a server on your local machine. In general this is the safest way to get a large range of values from a server buffer into the client app.
code::
s.boot;
b = Buffer.read(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav");
// same as Buffer.plot
b.loadToFloatArray(action: { arg array; a = array; {a.plot;}.defer; "done".postln;});
b.free;
::
method:: getToFloatArray
Stream the buffer to the client using a series of getn messages and put the results into a FloatArray.
argument:: index
The index in the buffer to begin writing from. The default is 0.
argument:: count
The number of values to write. The default is -1, which writes from index until the end of the buffer.
argument:: wait
The amount of time in seconds to wait between sending getn messages. Longer times are safer. The default is 0.01 seconds which seems reliable under normal circumstances. A setting of 0 is not recommended.
argument:: timeout
The amount of time in seconds after which to post a warning if all replies have not yet been received. the default is 3.
argument:: action
A Function which will be passed the resulting FloatArray as an argument and evaluated when all replies have been received.
discussion::
This is more risky than loadToFloatArray but does works with servers on remote machines. In high traffic situations it is possible for data to be lost. If this method has not received all its replies by timeout it will post a warning saying that the method has failed. In general use loadToFloatArray instead wherever possible.
code::
s.boot;
b = Buffer.read(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav");
// like Buffer.plot
b.getToFloatArray(wait:0.01,action:{arg array; a = array; {a.plot;}.defer;"done".postln;});
b.free;
::
method:: normalize, normalizeMsg
Normalizes the buffer so that the peak absolute value is newmax (which defaults to 1). If your buffer is in Wavetable format then set the asWavetable argument to true.
method:: fill, fillMsg
Starting at the index startAt, set the next numFrames to value. Additional ranges may be included in the same message.
method:: copyData, copyMsg
Starting at the index srcStartAt, copy numSamples samples from this to the destination buffer buf starting at dstStartAt. If numSamples is negative, the maximum number of samples possible is copied. The default is start from 0 in the source and copy the maximum number possible starting at 0 in the destination.
discussion::
Note: This method used to be called copy, but this conflicts with the method for object-copying. Therefore Buffer:copy is now intended to create a copy of the client-side Buffer object. Its use for copying buffer data on the server is deprecated. If you see a deprecation warning, the data will still be copied on the server and your code will still work, but you should update your code for the new method name.
code::
s.boot;
(
SynthDef(\help_Buffer_copy, {
arg out = 0, buf;
Line.ar(0, 0, dur: BufDur.kr(buf), doneAction: Done.freeSelf);
Out.ar(out, PlayBuf.ar(1, buf));
}).add;
)
(
b = Buffer.read(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav");
c = Buffer.alloc(s, 120000);
)
Synth(\help_Buffer_copy, [\buf, b]);
// copy the whole buffer
b.copyData(c);
Synth(\help_Buffer_copy, [\buf, c]);
// copy some samples
c.zero;
b.copyData(c, numSamples: 4410);
Synth(\help_Buffer_copy, [\buf, c]);
// buffer "compositing"
c.zero;
b.copyData(c, numSamples: 4410);
b.copyData(c, dstStartAt: 4410, numSamples: 15500);
Synth(\help_Buffer_copy, [\buf, c]);
b.free;
c.free;
::
method:: close, closeMsg
After using a Buffer with a DiskOut or DiskIn, it is necessary to close the soundfile. Failure to do so can cause problems.
argument:: completionMessage
A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
method:: plot
Plot the contents of the Buffer in a GUI window.
argument:: name
The name of the resulting window.
argument:: bounds
An instance of Rect determining the size of the resulting view.
argument:: minval
the minimum value in the plot
argument:: maxval
the maximum value in the plot
argument:: parent
a window to place the plot in. If nil, one will be created for you
discussion::
code::
s.boot;
b = Buffer.read(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav");
b.plot;
b.free;
::
method:: play
Plays the contents of the buffer on the server and returns a corresponding Synth.
argument:: loop
A Boolean indicating whether or not to loop playback. If false the synth will automatically be freed when done. The default is false.
argument:: mul
A value by which to scale the output. The default is 1.
discussion::
code::
s.boot;
b = Buffer.read(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav");
b.play; // frees itself
x = b.play(true);
x.free; b.free;
::
method:: query
Sends a b_query message to the server, asking for a description of this buffer. The results are posted to the post window. Does not update instance vars.
method:: updateInfo
Sends a b_query message to the server, asking for a description of this buffer. Upon reply this Buffer's instance variables are automatically updated.
argument:: action
A Function to be evaluated once the file has been read and this Buffer's instance variables have been updated. The function will be passed this Buffer as an argument.
discussion::
code::
s.boot;
b = Buffer.readNoUpdate(s, Platform.resourceDir +/+ "sounds/a11wlk01.wav");
b.numFrames; // incorrect, shows nil
b.updateInfo({|buf| buf.numFrames.postln; }); // now it's right
b.free;
::
subsection:: Buffer Fill Commands
These correspond to the various b_gen OSC Commands, which fill the buffer with values for use. See link::Reference/Server-Command-Reference:: for more details.
method:: gen, genMsg
This is a generalized version of the commands below.
argument:: genCommand
A String indicating the name of the command to use. See Server-Command-Reference for a list of valid command names.
argument:: genArgs
An Array containing the corresponding arguments to the command.
argument:: normalize
A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
argument:: asWavetable
A Boolean indicating whether or not to write to the buffer in wavetable format so that it can be read by interpolating oscillators. The default is true.
argument:: clearFirst
A Boolean indicating whether or not to clear the buffer before writing. The default is true.
method:: sine1, sine1Msg
Fill this buffer with a series of sine wave harmonics using specified amplitudes.
argument:: amps
An Array containing amplitudes for the harmonics. The first float value specifies the amplitude of the first partial, the second float value specifies the amplitude of the second partial, and so on.
argument:: normalize
A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
argument:: asWavetable
A Boolean indicating whether or not to write to the buffer in wavetable format so that it can be read by interpolating oscillators. The default is true.
argument:: clearFirst
A Boolean indicating whether or not to clear the buffer before writing. The default is true.
discussion::
code::
s.boot;
(
b = Buffer.alloc(s, 512, 1);
b.sine1(1.0 / [1, 2, 3, 4], true, true, true);
x = { Osc.ar(b, 200, 0, 0.5) }.play;
)
x.free; b.free;
::
method:: sine2, sine2Msg
Fill this buffer with a series of sine wave partials using specified frequencies and amplitudes.
argument:: freqs
An Array containing frequencies (in cycles per buffer) for the partials.
argument:: amps
An Array containing amplitudes for the partials. This should contain the same number of items as freqs.
argument:: normalize
A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
argument:: asWavetable
A Boolean indicating whether or not to write to the buffer in wavetable format so that it can be read by interpolating oscillators. The default is true.
argument:: clearFirst
A Boolean indicating whether or not to clear the buffer before writing. The default is true.
discussion::
code::
s.boot;
(
b = Buffer.alloc(s, 512, 1);
b.sine2([1.0, 3], [1, 0.5]);
x = { Osc.ar(b, 200, 0, 0.5) }.play;
)
x.free; b.free;
::
method:: sine3, sine3Msg
Fill this buffer with a series of sine wave partials using specified frequencies, amplitudes, and initial phases.
argument:: freqs
An Array containing frequencies (in cycles per buffer) for the partials.
argument:: amps
An Array containing amplitudes for the partials. This should contain the same number of items as freqs.
argument:: phases
An Array containing initial phase for the partials (in radians). This should contain the same number of items as freqs.
argument:: normalize
A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
argument:: asWavetable
A Boolean indicating whether or not to write to the buffer in wavetable format so that it can be read by interpolating oscillators. The default is true.
argument:: clearFirst
A Boolean indicating whether or not to clear the buffer before writing. The default is true.
method:: cheby, chebyMsg
Fill this buffer with a series of Chebyshev polynomials, which can be defined as: code::cheby(n) = amplitude * cos(n * acos(x))::. To eliminate a DC offset when used as a waveshaper, the wavetable is offset so that the center value is zero.
Similar functionality can be found in link::Classes/Signal#*chebyFill#Signal.chebyFill:: and link::Classes/Wavetable#*chebyFill#Wavetable.chebyFill::. If you require Chebyshev polynomials that do not include the offset compensation, it is recommended to use one of these.
argument:: amplitudes
An Array containing amplitudes for the harmonics. The first float value specifies the amplitude for n = 1, the second float value specifies the amplitude for n = 2, and so on.
argument:: normalize
A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
argument:: asWavetable
A Boolean indicating whether or not to write to the buffer in wavetable format so that it can be read by interpolating oscillators. The default is true.
argument:: clearFirst
A Boolean indicating whether or not to clear the buffer before writing. The default is true.
discussion::
note::
In previous versions, offsetting (to ensure the center value is zero) was performed incorrectly. This was fixed in version 3.7, so any code that may have relied on the (wrong) behavior may need to be changed. If using a Chebyshev buffer as a waveshaper, the simplest fix is to wrap the link::Classes/Shaper:: in a link::Classes/LeakDC:: UGen.
::
code::
s.boot;
b = Buffer.alloc(s, 512, 1, {arg buf; buf.chebyMsg([1,0,1,1,0,1])});
(
x = {
Shaper.ar(
b,
SinOsc.ar(300, 0, Line.kr(0,1,6)),
0.5
)
}.play;
)
x.free; b.free;
::