oneShot: free the responder before running user func (avoid error)
[supercollider.git] / HelpSource / Classes / Buffer.schelp
blob439bad3ddf8dca15fa2e6b09fabaea7f2a049588
1 class:: Buffer
2 summary:: Client-side representation of a buffer on a server
3 categories:: Server>Abstractions
5 description::
7 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.
9 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.
11 Buffer objects should not be created or modified within a link::Classes/SynthDef::. If this is needed, see link::Classes/LocalBuf::.
13 subsection:: Buffer Numbers and Allocation
15 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.) 
17 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.
19 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.
21 subsection:: Multichannel Buffers
23 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::.
24 Indices start at 0 and go up to code:: (numFrames * numChannels) - 1 ::.
25 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.
27 In some cases it is simpler to use multiple single channel buffers instead of a single multichannel one.
29 subsection:: Completion Messages and Action Functions
31 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.
32 Since they can last an aribitrary amount of time it is convenient to be able to specify something else that can be done immediately on completion.
33 The ability to do this is implemented in two ways in Buffer's various methods: completion messages and action functions. 
35 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.)
36 The server will execute this immediately upon completing the first command.
37 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.
38 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.
40 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.
41 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.
43 subsection:: Bundling
45 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.
46 It is also possible to capture the messages generated by the regular methods using Server's automated bundling capabilities.
47 See link::Classes/Server:: and link::Guides/Bundled-Messages:: for more details.
49 classmethods::
50 private:: initClass, initServerCache, clearServerCaches
52 subsection:: Creation with Immediate Memory Allocation
54 method:: alloc
55 Create and return a Buffer and immediately allocate the required memory on the server. The buffer's values will be initialised to 0.0.
56 argument:: server
57 The server on which to allocate the buffer. The default is the default Server.
58 argument:: numFrames
59 The number of frames to allocate. Actual memory use will correspond to numFrames * numChannels.
60 argument:: numChannels
61 The number of channels for the Buffer. The default is 1.
62 argument:: completionMessage
63 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
64 argument:: bufnum
65 An explicitly specified buffer number. Generally this is not needed.
66 discussion::
67 code::
68 // Allocate 8 second stereo buffer
69 s.boot;
70 b = Buffer.alloc(s, s.sampleRate * 8.0, 2);
71 b.free;
73         
74 method:: allocConsecutive
75 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.
76 argument:: numBufs
77 The number of consecutively indexed buffers to allocate.
78 argument:: server
79 The server on which to allocate the buffers. The default is the default Server.
80 argument:: numFrames
81 The number of frames to allocate in each buffer. Actual memory use will correspond to numFrames * numChannels.
82 argument:: numChannels
83 The number of channels for each buffer. The default is 1.
84 argument:: completionMessage
85 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.
86 argument:: bufnum
87 An explicitly specified buffer number for the initial buffer. Generally this is not needed.
88 discussion::
89 N.B. You must treat the array of Buffers as a group. Freeing them individually or resuing them can result in allocation errors. You should free all Buffers in the array at the same time by iterating over it with do.
90 code::
91 s.boot;
92 // allocate an array of Buffers and fill them with different harmonics
94 b = Buffer.allocConsecutive(8, s, 4096, 1, { |buf, i|
95         buf.sine1Msg((1..((i+1)*6)).reciprocal) // completion Messages
96 });
98 a = { VOsc.ar(SinOsc.kr(0.5, 0).range(b.first.bufnum + 0.1, b.last.bufnum - 0.1),
99         [440, 441], 0, 0.2) }.play;
101 a.free; 
103 // iterate over the array and free it
104 b.do(_.free);
107 method:: read
108 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.
109 argument:: server
110 The server on which to allocate the buffer.
111 argument:: path
112 A String representing the path of the soundfile to be read.
113 argument:: startFrame
114 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
115 argument:: numFrames
116 The number of frames to read. The default is -1, which will read the whole file.
117 argument:: action
118 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.
119 argument:: bufnum
120 An explicitly specified buffer number. Generally this is not needed.
121                 
122 discussion::
123 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.
124 code::
125 // read a soundfile
126 s.boot;
127 b = Buffer.read(s, "sounds/a11wlk01.wav");
129 // now play it
131 x = SynthDef(\help_Buffer, { arg out = 0, bufnum;
132     Out.ar( out,
133             PlayBuf.ar(1, bufnum, BufRateScale.kr(bufnum))
134     )
135 }).play(s,[\bufnum, b]);
137 x.free; b.free;
139 // with an action function
140 // note that the vars are not immediately up-to-date
142 b = Buffer.read(s, "sounds/a11wlk01.wav", action: { arg buffer; 
143     ("After update:" + buffer.numFrames).postln;
144     x = { PlayBuf.ar(1, buffer, BufRateScale.kr(buffer)) }.play;
146 ("Before update:" + b.numFrames).postln;
148 x.free; b.free;
151 method:: readChannel
152 As code::read:: above, but takes an link::Classes/Array:: of channel indices to read in, allowing one to read only the selected channels.
153 argument:: server
154 The server on which to allocate the buffer.
155 argument:: path
156 A String representing the path of the soundfile to be read.
157 argument:: startFrame
158 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
159 argument:: numFrames
160 The number of frames to read. The default is -1, which will read the whole file.
161 argument:: channels
162 An Array of channels to be read from the soundfile. Indices start from zero. These will be read in the order provided.
163 argument:: action
164 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.
165 argument:: bufnum
166 An explicitly specified buffer number. Generally this is not needed.
167 discussion::
168 code::
169 s.boot;
170 // first a standard read so we can see what's in the file
171 b = Buffer.read(s, "sounds/SinedPink.aiff");
172 // "sounds/SinedPink.aiff" contains SinOsc on left, PinkNoise on right
173 b.plot;
174 b.free;
176 // Now just the sine
177 b = Buffer.readChannel(s, "sounds/SinedPink.aiff", channels: [0]);
178 b.plot;
179 b.free;
181 // Now just the pink noise
182 b = Buffer.readChannel(s, "sounds/SinedPink.aiff", channels: [1]);
183 b.plot;
184 b.free;
186 // Now reverse channel order
187 b = Buffer.readChannel(s, "sounds/SinedPink.aiff", channels: [1, 0]);
188 b.plot;
189 b.free;
192 method:: readNoUpdate
193 As code::read:: above, but without the automatic update of instance variables. Call code::updateInfo:: (see below) to update the vars.
194 argument:: server
195 The server on which to allocate the buffer.
196 argument:: path
197 A String representing the path of the soundfile to be read.
198 argument:: startFrame
199 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
200 argument:: numFrames
201 The number of frames to read. The default is -1, which will read the whole file.
202 argument:: completionMessage
203 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
204 argument:: bufnum
205 An explicitly specified buffer number. Generally this is not needed.
206 discussion::
207 code::
208 // with a completion message                    
209 s.boot;
211 SynthDef(\help_Buffer,{ arg out=0, bufnum;
212         Out.ar( out,
213                 PlayBuf.ar(1,bufnum,BufRateScale.kr(bufnum))
214         )
215 }).add;
217 y = Synth.basicNew(\help_Buffer); // not sent yet
218 b = Buffer.readNoUpdate(s,"sounds/a11wlk01.wav", 
219         completionMessage: { arg buffer;
220                 // synth add its s_new msg to follow 
221                 // after the buffer read completes
222                 y.newMsg(s,[\bufnum, buffer],\addToTail)
223         });
225 // note vars not accurate
226 b.numFrames; // nil
227 b.updateInfo;
228 b.numFrames; // 188893
229 // when done...
230 y.free;
231 b.free;
234 method:: cueSoundFile
235 Allocate a buffer and preload a soundfile for streaming in using link::Classes/DiskIn::.
236 argument:: server
237 The server on which to allocate the buffer.
238 argument:: path
239 A String representing the path of the soundfile to be read.
240 argument:: startFrame
241 The frame of the soundfile that DiskIn will start playing at.
242 argument:: numChannels
243 The number of channels in the soundfile.
244 argument:: bufferSize
245 This must be a multiple of  (2 * the server's block size). 32768 is the default and is suitable for most cases.
246 argument:: completionMessage
247 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
248 discussion::
249 code::
250 s.boot;
252 SynthDef(\help_Buffer_cue,{ arg out=0,bufnum;
253         Out.ar(out,
254                 DiskIn.ar( 1, bufnum )
255         )
256 }).add;
260 s.makeBundle(nil, {
261         b = Buffer.cueSoundFile(s,"sounds/a11wlk01-44_1.aiff", 0, 1);
262         y = Synth(\help_Buffer_cue, [\bufnum, b], s);
265 b.free; y.free;
268 method:: loadCollection
269 Load a large collection into a buffer on the server. Returns a Buffer object.
270 argument:: server
271 The server on which to create the buffer.
272 argument:: collection
273 A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
274 argument:: numChannels
275 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.
276 argument:: action
277 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.
279 discussion::
280 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.
281 code::
282 s.boot;
284 a = FloatArray.fill(44100 * 5.0, {1.0.rand2}); // 5 seconds of noise
285 b = Buffer.loadCollection(s, a);
288 // test it
289 b.get(20000,{|msg| (msg == a[20000]).postln});
290 // play it
291 x = { PlayBuf.ar(1, b, BufRateScale.kr(b), loop: 0) * 0.5 }.play;
292 b.free; x.free;
294 // interleave a multi-dimensional array
296 l = Signal.sineFill(16384, Array.fill(200, {0}).add(1));
297 r = Array.fill(16384, {1.0.rand2});
298 m = [Array.newFrom(l), r]; // a multi-dimensional array
299 m = m.lace(32768); // interleave the two collections 
300 b = Buffer.loadCollection(s, m, 2, {|buf|
301         x = { PlayBuf.ar(2, buf, BufRateScale.kr(buf), loop: 1) * 0.5 }.play;
304 b.plot;
305 x.free; b.free;
307                 
308 method:: sendCollection
309 Stream a large collection into a buffer on the server using multiple setn messages. Returns a Buffer object.
310 argument:: server
311 The server on which to create the buffer.
312 argument:: collection
313 A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
314 argument:: numChannels
315 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 *loadCollection, above, to see how to do this.
316 argument:: wait
317 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.
318 argument:: action
319 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.
320 discussion::
321 This allows for larger collections than setn, below. This is not as safe as code::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.
322 code::
323 s.boot;
325 a = Array.fill(2000000,{ rrand(0.0,1.0) }); // a LARGE collection
326 b = Buffer.sendCollection(s, a, 1, 0, {arg buf; "finished".postln;});
328 b.get(1999999, {|msg| (msg == a[1999999]).postln});
329 b.free;
332 method:: loadDialog
333 As code::read:: above, but gives you a load dialog window to browse for a file. Cocoa and SwingOSC compatible.
334 argument:: server
335 The server on which to allocate the buffer.
336 argument:: startFrame
337 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
338 argument:: numFrames
339 The number of frames to read. The default is -1, which will read the whole file.
340 argument:: action
341 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.
342 argument:: bufnum
343 An explicitly specified buffer number. Generally this is not needed.
344 discussion::
345 code::
346 s.boot;
348 b = Buffer.loadDialog(s, action: { arg buffer; 
349         x = { PlayBuf.ar(buffer.numChannels, buffer, BufRateScale.kr(buffer)) }.play;
352 x.free; b.free;
355 subsection:: Creation without Immediate Memory Allocation
356 method:: new
357 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.
358 argument:: server
359 The server on which to allocate the buffer. The default is the default Server.
360 argument:: numFrames
361 The number of frames to allocate. Actual memory use will correspond to numFrames * numChannels.
362 argument:: numChannels
363 The number of channels for the Buffer. The default is 1.
364 argument:: bufnum
365 An explicitly specified buffer number. Generally this is not needed.
366 discussion::
367 code::
368 s.boot;
369 b = Buffer.new(s, 44100 * 8.0, 2);
370 c = Buffer.new(s, 44100 * 4.0, 2);
371 b.query; // numFrames = 0
372 s.sendBundle(nil, b.allocMsg, c.allocMsg); // sent both at the same time
373 b.query; // now it's right
374 c.query;
375 b.free; c.free;
378 subsection:: Cached Buffers
380 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.
381 Freeing a buffer removes it from the cache; quitting the server clears all the cached buffers. (This also occurs if the server crashes unexpectedly.)
383 You may access cached buffers using the following methods.
385 It may be simpler to access them through the server object:
386 code::
387 myServer.cachedBufferAt(bufnum)
388 myServer.cachedBuffersDo(func)
390 b = Buffer.alloc(s, 2048, 1);
391 Buffer.cachedBufferAt(s, 0);    // assuming b has bufnum 0
392 s.cachedBufferAt(0);                    // same result
393 s.cachedBuffersDo({ |buf| buf.postln });
396 method:: cachedBufferAt
397 Access a buffer by its number.
399 method:: cachedBuffersDo
400 Iterate over all cached buffers. The iteration is not in any order, but will touch all buffers.
402         
403 InstanceMethods::
405 subsection:: Variables
407 The following variables have getter methods.
409 method:: server
410 Returns the Buffer's Server object.
411         
412 method:: bufnum
413 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.
414 discussion::
415 code::
416 s.boot;
417 b = Buffer.alloc(s,44100 * 8.0,2);
418 b.bufnum.postln;
419 b.free;
422 method:: numFrames
423 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.
424         
425 method:: numChannels
426 Returns the number of channels in the corresponding server-side buffer. 
427         
428 method:: sampleRate
429 Returns the sample rate of the corresponding server-side buffer.
430         
431 method:: path
432 Returns a string containing the path of a soundfile that has been loaded into the corresponding server-side buffer.
433         
435 subsection:: Explicit allocation
437 These methods allocate the necessary memory on the server for a Buffer previously created with code::new::, above.
439 method:: alloc, allocMsg
440 argument:: completionMessage
441 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
442 discussion::
443 code::
444 s.boot;
445 b = Buffer.new(s, 44100 * 8.0, 2);
446 b.query; // numFrames = 0
447 b.alloc;
448 b.query; // numFrames = 352800
449 b.free;
452 method:: allocRead, allocReadMsg
453 Read a soundfile into a buffer on the server for a Buffer previously created with *new, above. Note that this will not autoupdate instance variables. Call code::updateInfo:: in order to do this.
454 argument:: argpath
455 A String representing the path of the soundfile to be read.
456 argument:: startFrame
457 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
458 argument:: numFrames
459 The number of frames to read. The default is -1, which will read the whole file.
460 argument:: completionMessage
461 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
462 discussion::
463 code::
464 s.boot;
465 b = Buffer.new(s);
466 b.allocRead("sounds/a11wlk01.wav");
467 x = { PlayBuf.ar(1, b, BufRateScale.kr(b), loop: 1) * 0.5 }.play;
468 x.free; b.free;
471 method:: allocReadChannel, allocReadChannelMsg
472 As allocRead above, but allows you to specify which channels to read.
473 argument:: argpath
474 A String representing the path of the soundfile to be read.
475 argument:: startFrame
476 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
477 argument:: numFrames
478 The number of frames to read. The default is -1, which will read the whole file.
479 argument:: channels
480 An Array of channels to be read from the soundfile. Indices start from zero. These will be read in the order provided.
481 argument:: completionMessage
482 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
483 discussion::
484 code::
485 s.boot;
486 b = Buffer.new(s);
487 // read only the first channel (a Sine wave) of a stereo file
488 b.allocReadChannel("sounds/SinedPink.aiff", channels: [0]);
489 x = { PlayBuf.ar(1, b, BufRateScale.kr(b), loop: 1) * 0.5 }.play;
490 x.free; b.free;         
493 subsection:: Other methods
495 method:: read, readMsg
496 Read a soundfile into an already allocated buffer.
497 argument:: path
498 A String representing the path of the soundfile to be read.
499 argument:: fileStartFrame
500 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
501 argument:: numFrames
502 The number of frames to read. The default is -1, which will read the whole file.
503 argument:: bufStartFrame
504 The index of the frame in the buffer at which to start reading. The default is 0, which is the beginning of the buffer.
505 argument:: leaveOpen
506 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).
507 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.
508 argument:: action
509 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.
510 argument:: completionMessage
511 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
513 discussion::
514 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.
515                 
516 method:: readChannel, readChannelMsg
517 As read above, but allows you to specify which channels to read.
518 argument:: path
519 A String representing the path of the soundfile to be read.
520 argument:: fileStartFrame
521 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
522 argument:: numFrames
523 The number of frames to read. The default is -1, which will read the whole file.
524 argument:: bufStartFrame
525 The index of the frame in the buffer at which to start reading. The default is 0, which is the beginning of the buffer.
526 argument:: leaveOpen
527 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).
528 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.
529 argument:: channels
530 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.
531 argument:: action
532 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.
533 argument:: completionMessage
534 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
535                 
536 method:: cueSoundFile, cueSoundFileMsg
537 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.
538 argument:: path
539 A String representing the path of the soundfile to be read.
540 argument:: startFrame
541 The first frame of the soundfile to read. The default is 0, which is the beginning of the file.
542 argument:: completionMessage
543 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
544 discussion::
545 code::
546 s.boot;
547 //create with cueSoundFile class method
548 b = Buffer.cueSoundFile(s, "sounds/a11wlk01-44_1.aiff", 0, 1);
549 x = { DiskIn.ar(1, b) }.play;   
550 b.close;        // must call close in between cueing
551 // now use like named instance method, but different arguments
552 b.cueSoundFile("sounds/a11wlk01-44_1.aiff");    
553 // have to do all this to clean up properly!    
554 x.free; b.close; b.free;        
556         
557 method:: write, writeMsg
558 Write the contents of the buffer to a file. See link::Classes/SoundFile:: for information on valid values for headerFormat and sampleFormat.
559 argument:: path
560 A String representing the path of the soundfile to be written.
561 If no path is given, Buffer writes into the default recording directory with a generic name.
562 argument:: numFrames
563 The number of frames to write. The default is -1, which will write the whole buffer.
564 argument:: startFrame
565 The index of the frame in the buffer from which to start writing. The default is 0, which is the beginning of the buffer.
566 argument:: leaveOpen
567 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.
568 argument:: completionMessage
569 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
571 method:: free, freeMsg
572 Release the buffer's memory on the server and return the bufferID back to the server's buffer number allocator for future reuse.
573 argument:: completionMessage
574 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
576 method:: zero, zeroMsg
577 Sets all values in this buffer to 0.0.
578 argument:: completionMessage
579 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
581 method:: set, setMsg
582 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. 
583 discussion::
584 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.
585 code::
586 s.boot;
587 b = Buffer.alloc(s, 4, 2);
588 b.set(0, 0.2, 1, 0.3, 7, 0.4); // set the values at indices 0, 1, and 7.
589 b.getn(0, 8, {|msg| msg.postln});
590 b.free; 
593 method:: setn, setnMsg
594 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.
595 discussion::
596 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.
598 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 code::loadCollection:: and code::sendCollection:: to set larger ranges of values.
599 code::
600 s.boot;
601 b = Buffer.alloc(s,16);
602 b.setn(0, Array.fill(16, { rrand(0,1) }));
603 b.getn(0, b.numFrames, {|msg| msg.postln});
604 b.setn(0, [1, 2, 3], 4, [1, 2, 3]);
605 b.getn(0, b.numFrames, {|msg| msg.postln});
606 b.free;
609 method:: loadCollection
610 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.
611 argument:: collection
612 A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
613 argument:: startFrame
614 The index of the frame at which to start loading the collection. The default is 0, which is the start of the buffer.
615 argument:: action
616 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.
618 discussion::
619 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.
620 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. 
621 code::
622 s.boot;
624 v = Signal.sineFill(128, 1.0/[1,2,3,4,5,6]);
625 b = Buffer.alloc(s, 128);
628 b.loadCollection(v, action: {|buf| 
629         x = { PlayBuf.ar(buf.numChannels, buf, BufRateScale.kr(buf), loop: 1) 
630                 * 0.2 }.play;
633 x.free; b.free;
634                 
635 // interleave a multi-dimensional array
637 l = Signal.sineFill(16384, Array.fill(200, {0}).add(1));
638 r = Array.fill(16384, {1.0.rand2});
639 m = [Array.newFrom(l), r]; // a multi-dimensional array
640 m = m.lace(32768); // interleave the two collections 
641 b = Buffer.alloc(s, 16384, 2);
644 b.loadCollection(m, 0, {|buf|
645         x = { PlayBuf.ar(2, buf, BufRateScale.kr(buf), loop: 1) * 0.5 }.play;
648 b.plot;
649 x.free; b.free;
652 method:: sendCollection
653 Stream a large collection into this buffer using multiple setn messages.
654 argument:: collection
655 A subclass of Collection (i.e. an Array) containing only floats and integers. Multi-dimensional arrays will not work.
656 argument:: startFrame
657 The index of the frame at which to start streaming in the collection. The default is 0, which is the start of the buffer.
658 argument:: wait
659 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.
660 argument:: action
661 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.
662 discussion::
663 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.
664 code::
665 s.boot;
667 a = Array.fill(2000000,{ rrand(0.0,1.0) });
668 b = Buffer.alloc(s, 2000000);
670 b = b.sendCollection(a, action: {arg buf; "finished".postln;});
671 b.get(1999999, {|msg| (msg == a[1999999]).postln});
672 b.free;
675 method:: get, getMsg
676 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.
677 discussion::
678 code::
679 s.boot;
680 b = Buffer.alloc(s,16);
681 b.setn(0, Array.fill(16, { rrand(0.0, 1.0) }));
682 b.get(0, {|msg| msg.postln});
683 b.free;
686 method:: getn, getMsg
687 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. 
688 discussion::            
689 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 loadToFloatArray and getToFloatArray to get larger ranges of values.
691 method:: loadToFloatArray
692 Write the buffer to a file and then load it into a FloatArray.
693 argument:: index
694 The index in the buffer to begin writing from. The default is 0.
695 argument:: count
696 The number of values to write. The default is -1, which writes from index until the end of the  buffer.
697 argument:: action
698 A Function which will be passed the resulting FloatArray as an argument and evaluated when loading is finished.
699 discussion::
700 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.
701 code::
702 s.boot;
703 b = Buffer.read(s,"sounds/a11wlk01.wav");
704 // same as Buffer.plot
705 b.loadToFloatArray(action: { arg array; a = array; {a.plot;}.defer; "done".postln;});
706 b.free;
709 method:: getToFloatArray
710 Stream the buffer to the client using a series of getn messages and put the results into a FloatArray.
711 argument:: index
712 The index in the buffer to begin writing from. The default is 0.
713 argument:: count
714 The number of values to write. The default is -1, which writes from index until the end of the  buffer.
715 argument:: wait
716 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.
717 argument:: timeout
718 The amount of time in seconds after which to post a warning if all replies have not yet been received. the default is 3.
719 argument:: action
720 A Function which will be passed the resulting FloatArray as an argument and evaluated when all replies have been received.
721 discussion::
722 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.
723 code::
724 s.boot;
725 b = Buffer.read(s,"sounds/a11wlk01.wav");
726 // like Buffer.plot
727 b.getToFloatArray(wait:0.01,action:{arg array; a = array; {a.plot;}.defer;"done".postln;});
728 b.free;
731 method:: normalize, normalizeMsg
732 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.
733         
734 method:: fill, fillMsg
735 Starting at the index startAt, set the next numFrames to value. Additional ranges may be included in the same message.
736         
737 method:: copyData, copyMsg
738 Starting at the index srcSamplePos, copy numSamples samples from this to the destination buffer buf starting at dstSamplePos. 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.
739 discussion::
740 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.
741 code::
742 s.boot;
744 SynthDef(\help_Buffer_copy, { arg out=0, buf;
745         Line.ar(0, 0, dur: BufDur.kr(buf), doneAction: 2); // frees itself
746         Out.ar(out, PlayBuf.ar(1, buf));
747 }).add;
751 b = Buffer.read(s, "sounds/a11wlk01.wav");
752 c = Buffer.alloc(s, 120000);
755 Synth(\help_Buffer_copy, [\buf, b]);            
757 // copy the whole buffer
758 b.copyData(c);
759 Synth(\help_Buffer_copy, [\buf, c]);
761 // copy some samples
762 c.zero;                                                         
763 b.copyData(c, numSamples: 4410);
764 Synth(\help_Buffer_copy, [\buf, c]);
766 // buffer "compositing"
767 c.zero;                                                         
768 b.copyData(c, numSamples: 4410);
769 b.copyData(c, dstStartAt: 4410, numSamples: 15500);
770 Synth(\help_Buffer_copy, [\buf, c]);
772 b.free;
773 c.free;
776 method:: close, closeMsg
777 After using a Buffer with a DiskOut or DiskIn, it is necessary to close the soundfile. Failure to do so can cause problems.
778 argument:: completionMessage
779 A valid OSC message or a Function which will return one. A Function will be passed this Buffer as an argument when evaluated.
780         
781 method:: plot
782 Plot the contents of the Buffer in a GUI window.
783 argument:: name
784 The name of the resulting window.
785 argument:: bounds
786 An instance of Rect determining the size of the resulting view.
787 argument:: minval
788 the minimum value in the plot
789 argument:: maxval
790 the maximum value in the plot
791 argument:: parent
792 a window to place the plot in. If nil, one will be created for you
793 discussion::
794 code::
795 s.boot;
796 b = Buffer.read(s,"sounds/a11wlk01.wav");
797 b.plot;
798 b.free;
801 method:: play
802 Plays the contents of the buffer on the server and returns a corresponding Synth.
803 argument:: loop
804 A Boolean indicating whether or not to loop playback. If false the synth will automatically be freed when done. The default is false.
805 argument:: mul
806 A value by which to scale the output. The default is 1.
807 discussion::
808 code::
809 s.boot;
810 b = Buffer.read(s,"sounds/a11wlk01.wav");
811 b.play; // frees itself
812 x = b.play(true);
813 x.free; b.free;
816 method:: query
817 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.
819 method:: updateInfo
820 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.
821 argument:: action
822 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.
823 discussion::
824 code::
825 s.boot;
826 b = Buffer.readNoUpdate(s, "sounds/a11wlk01.wav");
827 b.numFrames; // incorrect, shows nil
828 b.updateInfo({|buf| buf.numFrames.postln; }); // now it's right
829 b.free;
832 subsection:: Buffer Fill Commands
833 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.
835 method:: gen, genMsg
836 This is a generalized version of the commands below.
837 argument:: genCommand
838 A String indicating the name of the command to use. See Server-Command-Reference for a list of valid command names.
839 argument:: genArgs
840 An Array containing the corresponding arguments to the command.
841 argument:: normalize
842 A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
843 argument:: asWavetable
844 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.
845 argument:: clearFirst
846 A Boolean indicating whether or not to clear the buffer before writing. The default is true.
848 method:: sine1, sine1Msg
849 Fill this buffer with a series of sine wave harmonics using specified amplitudes.
850 argument:: amps
851 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.
852 argument:: normalize
853 A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
854 argument:: asWavetable
855 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.
856 argument:: clearFirst
857 A Boolean indicating whether or not to clear the buffer before writing. The default is true.
858 discussion::
859 code::
860 s.boot;
862 b = Buffer.alloc(s, 512, 1);
863 b.sine1(1.0 / [1, 2, 3, 4], true, true, true);
864 x = { Osc.ar(b, 200, 0, 0.5) }.play;
866 x.free; b.free;
869 method:: sine2, sine2Msg
870 Fill this buffer with a series of sine wave partials using specified frequencies and amplitudes.
871 argument:: freqs
872 An Array containing frequencies (in cycles per buffer) for the partials.
873 argument:: amps
874 An Array containing amplitudes for the partials. This should contain the same number of items as freqs.
875 argument:: normalize
876 A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
877 argument:: asWavetable
878 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.
879 argument:: clearFirst
880 A Boolean indicating whether or not to clear the buffer before writing. The default is true.
881 discussion::
882 code::
883 s.boot;
885 b = Buffer.alloc(s, 512, 1);
886 b.sine2([1.0, 3], [1, 0.5]);
887 x = { Osc.ar(b, 200, 0, 0.5) }.play;
889 x.free; b.free;
892 method:: sine3, sine3Msg
893 Fill this buffer with a series of sine wave partials using specified frequencies, amplitudes, and initial phases.
894 argument:: freqs
895 An Array containing frequencies (in cycles per buffer) for the partials.
896 argument:: amps
897 An Array containing amplitudes for the partials. This should contain the same number of items as freqs.
898 argument:: phases
899 An Array containing initial phase for the partials (in radians). This should contain the same number of items as freqs.
900 argument:: normalize
901 A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
902 argument:: asWavetable
903 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.
904 argument:: clearFirst
905 A Boolean indicating whether or not to clear the buffer before writing. The default is true.
907 method:: cheby, chebyMsg
908 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. 
909 argument:: amplitudes
910 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.
911 argument:: normalize
912 A Boolean indicating whether or not to normalize the buffer to a peak value of 1.0. The default is true.
913 argument:: asWavetable
914 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.
915 argument:: clearFirst
916 A Boolean indicating whether or not to clear the buffer before writing. The default is true.
917 discussion::
918 code::
919 s.boot;
920 b = Buffer.alloc(s, 512, 1, {arg buf; buf.chebyMsg([1,0,1,1,0,1])});
922 x = { 
923         Shaper.ar(
924                 b, 
925                 SinOsc.ar(300, 0, Line.kr(0,1,6)),
926                 0.5
927         ) 
928 }.play;
930 x.free; b.free;