File: 05-define-function.rst.txt

package info (click to toggle)
python-pyo 1.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,332 kB
  • sloc: python: 135,133; ansic: 127,822; javascript: 16,116; sh: 395; makefile: 388; cpp: 242
file content (57 lines) | stat: -rw-r--r-- 1,422 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Creating our own functions
============================================================================================================================================


**05-define-function.py**

The define keyword starts the definition of a custom function. The syntax is:

.. code-block:: scheme

    (define funcname (body))

`funcname` is the name used to call the function in the expression and body
is the sequence of expressions to execute. Arguments of the function are
extracted directly from the body. They must be named $1, $2, $3, …, $9.

The following example defines two functions, a simple oscillator and a
frequency modulation function using the former one.

.. code-block:: python

    from pyo import *
    
    s = Server().boot()
    
    expression = """
    // usage: (osc freq)
    (define osc (
            sin (* twopi (~ $1))
        )
    )
    
    // usage: (fm carrier ratio lfo_freq)
    (define fm (
            (let #car $1) // carrier
            (let #rat $2) // ratio
            (let #ind (+ (* (osc $3) 5) 5)) // lfo on the index
            (osc (+ #car (* (osc (* #car #rat)) (* #car (* #rat #ind)))))
        )
    )
    
    // Two FM generators.
    * (+ (fm 172 0.251 .1)
         (fm 86 0.499 .15)) 
      0.5
    
    """
    
    expr = Expr(Sig(0), expression, mul=0.5)
    expr.editor()
    
    sc = Scope(expr)
    
    pan = Pan(expr).out()
    
    s.gui(locals())