Debian Codegraph @

docs/_sources/examples/21-utilities/04-buffer-interface.rst.txt

raw
1 Sharing a table with a numpy array using the buffer protocol
2 ============================================================================================================================================
3
4
5 **04-buffer-interface.py**
6
7 This example shows two things:
8
9 1. How to share memory from a PyoTableObject to a numpy array with the
10 `getBuffer()` method of the PyoTableObject. Numpy functions can then
11 be used to modify the table's content without copying every samples.
12
13 2. How to register a `callback` function, with the `setCallback()` method
14 of the Server object, that the server will call at the beginning of
15 every processing loop (each `buffersize` samples).
16
17 .. note::
18
19 The numpy module **must** be installed for this example to work.
20
21 .. code-block:: python
22
23 from pyo import *
24 import numpy as np
25
26 s = Server().boot()
27
28 # Get the length of an audio block.
29 bs = s.getBufferSize()
30
31 # Create a table of length `buffer size` and read it in loop.
32 t = DataTable(size=bs)
33 osc = TableRead(t, freq=t.getRate(), loop=True, mul=0.1).out()
34
35 # Share the table's memory with a numpy array.
36 arr = np.asarray(t.getBuffer())
37
38
39 def process():
40 "Fill the array (so the table) with white noise."
41 arr[:] = np.random.normal(0.0, 0.5, size=bs)
42
43
44 # Register the `process` function to be called at the beginning
45 # of every processing loop.
46 s.setCallback(process)
47
48 s.gui(locals())
49