├── docs ├── CNAME ├── generate.py ├── page.html ├── github-markdown.css ├── content.md └── index.html ├── braid.egg-info ├── top_level.txt ├── dependency_links.txt ├── requires.txt ├── SOURCES.txt └── PKG-INFO ├── MANIFEST.in ├── package.sh ├── .gitattributes ├── braid ├── logger.py ├── __init__.py ├── custom.py ├── synths.yaml ├── core.py ├── midi.py ├── signal.py ├── notation.py ├── pattern.py ├── tween.py └── thread.py ├── .gitignore ├── README.md ├── setup.py ├── examples ├── 20181009.py ├── 20181008.py ├── 20181014.py ├── 20181012.py └── 20180804.py ├── CHANGELOG.md └── LICENSE.txt /docs/CNAME: -------------------------------------------------------------------------------- 1 | braid.live -------------------------------------------------------------------------------- /braid.egg-info/top_level.txt: -------------------------------------------------------------------------------- 1 | braid 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include braid/synths.yaml 2 | -------------------------------------------------------------------------------- /braid.egg-info/dependency_links.txt: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /package.sh: -------------------------------------------------------------------------------- 1 | python3 setup.py sdist 2 | rm -r dist 3 | -------------------------------------------------------------------------------- /braid.egg-info/requires.txt: -------------------------------------------------------------------------------- 1 | PyYAML>=3.11 2 | python-rtmidi>=1.0.0 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.js linguist-vendored=true 2 | *.html linguist-vendored=true -------------------------------------------------------------------------------- /braid/logger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import logging 4 | 5 | logger = logging.getLogger("braid") 6 | 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gitignore 2 | .DS_Store 3 | __pycache__ 4 | TODO.md 5 | shimring 6 | build 7 | dist 8 | examples/* 9 | recordings 10 | dev 11 | refs 12 | NOTES.md 13 | *backup.zip 14 | .idea 15 | *.code-workspace 16 | 17 | *.py 18 | !setup.py 19 | !*/*.py 20 | -------------------------------------------------------------------------------- /braid/__init__.py: -------------------------------------------------------------------------------- 1 | import inspect 2 | 3 | def num_args(f): 4 | """Returns the number of arguments received by the given function""" 5 | return len(inspect.getfullargspec(f).args) 6 | 7 | from .midi import midi_out 8 | 9 | from .thread import * 10 | from .signal import * 11 | from .core import * 12 | from . import custom 13 | 14 | def log_midi(value): 15 | midi.log_midi = True if value else False 16 | 17 | if LIVECODING: 18 | play() 19 | -------------------------------------------------------------------------------- /docs/generate.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os, markdown2 4 | 5 | with open(os.path.join(os.path.dirname(__file__), "page.html")) as f: 6 | page = f.read().strip() 7 | with open(os.path.join(os.path.dirname(__file__), "content.md")) as f: 8 | content = markdown2.markdown(f.read().strip(), extras=['fenced-code-blocks', 'codehilite']).replace(">>>", ">>>").replace("{{","").replace("}}","").replace("...", "...") 9 | with open(os.path.join(os.path.dirname(__file__), "index.html"), 'w') as f: 10 | f.write(page.replace("CONTENT", content)) 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Braid 2 | ===== 3 | 4 | Braid is a single-import module for Python 3 that comprises a sequencer and musical notation system for monophonic MIDI synths. Its emphasis is on interpolation, polyrhythms, phasing, and entrainment. 5 | 6 | Please see the [documentation](https://braid.live/). 7 | 8 | 9 | ### Copyright/License 10 | 11 | Copyright (c) 2013-2021 Brian House 12 | 13 | This program is free software licensed under the GNU General Public License, and you are welcome to redistribute it under certain conditions. It comes without any warranty whatsoever. See the LICENSE file for details, or see if it is missing. 14 | 15 | Please credit Brian House and link to https://brianhouse.net where appropriate. 16 | -------------------------------------------------------------------------------- /braid.egg-info/SOURCES.txt: -------------------------------------------------------------------------------- 1 | .gitattributes 2 | .gitignore 3 | CHANGELOG.md 4 | LICENSE.txt 5 | MANIFEST.in 6 | README.md 7 | package.sh 8 | setup.py 9 | braid/__init__.py 10 | braid/core.py 11 | braid/custom.py 12 | braid/midi.py 13 | braid/notation.py 14 | braid/pattern.py 15 | braid/signal.py 16 | braid/synths.yaml 17 | braid/thread.py 18 | braid/tween.py 19 | braid.egg-info/PKG-INFO 20 | braid.egg-info/SOURCES.txt 21 | braid.egg-info/dependency_links.txt 22 | braid.egg-info/requires.txt 23 | braid.egg-info/top_level.txt 24 | docs/CNAME 25 | docs/content.md 26 | docs/generate.py 27 | docs/github-markdown.css 28 | docs/index.html 29 | docs/page.html 30 | examples/20180804.py 31 | examples/20181008.py 32 | examples/20181009.py 33 | examples/20181012.py 34 | examples/20181014.py -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | from setuptools import setup 4 | 5 | with open("README.md", "r", encoding="utf-8") as fh: 6 | long_description = fh.read() 7 | 8 | setup( 9 | name="braid", 10 | version="0.14.1", 11 | author="Brian House", 12 | author_email="email@brian.house", 13 | description="A musical notation system and sequencer for monophonic MIDI synths.", 14 | long_description=long_description, 15 | long_description_content_type="text/markdown", 16 | url="https://braid.live", 17 | project_urls={ 18 | "Issue Tracker": "https://github.com/brianhouse/braid/issues", 19 | }, 20 | license='GPL3', 21 | packages=['braid'], 22 | include_package_data=True, 23 | install_requires=[ 24 | "python-rtmidi>=1.0.0", 25 | "PyYAML>=3.11" 26 | ], 27 | python_requires=">=3.7", 28 | ) 29 | -------------------------------------------------------------------------------- /braid.egg-info/PKG-INFO: -------------------------------------------------------------------------------- 1 | Metadata-Version: 2.1 2 | Name: braid 3 | Version: 0.14.1 4 | Summary: A musical notation system and sequencer for monophonic MIDI synths. 5 | Home-page: https://braid.live 6 | Author: Brian House 7 | Author-email: email@brian.house 8 | License: GPL3 9 | Project-URL: Issue Tracker, https://github.com/brianhouse/braid/issues 10 | Requires-Python: >=3.7 11 | Description-Content-Type: text/markdown 12 | License-File: LICENSE.txt 13 | 14 | Braid 15 | ===== 16 | 17 | Braid is a single-import module for Python 3 that comprises a sequencer and musical notation system for monophonic MIDI synths. Its emphasis is on interpolation, polyrhythms, phasing, and entrainment. 18 | 19 | Please see the [documentation](https://braid.live/). 20 | 21 | 22 | ### Copyright/License 23 | 24 | Copyright (c) 2013-2021 Brian House 25 | 26 | This program is free software licensed under the GNU General Public License, and you are welcome to redistribute it under certain conditions. It comes without any warranty whatsoever. See the LICENSE file for details, or see if it is missing. 27 | 28 | Please credit Brian House and link to https://brianhouse.net where appropriate. 29 | -------------------------------------------------------------------------------- /braid/custom.py: -------------------------------------------------------------------------------- 1 | from .logger import logger 2 | 3 | try: 4 | from . import Anode, Triode, VolcaKick, VolcaBeats, VolcaDrum, midi_out, midi_clamp 5 | except ImportError as e: 6 | logger.error("Custom Threads failed: %s" % e) 7 | else: 8 | 9 | from braid.notation import * 10 | 11 | """ 12 | Volcas dont respond to note velocity, unfortunately, but we can simulate it with these customizations. 13 | 14 | Would rather not have this in the module itself, but so be it. 15 | 16 | """ 17 | 18 | def note(self, pitch, velocity): 19 | midi_out.send_note(self._channel, self._previous_pitch, 0) 20 | midi_out.send_control(self._channel, 44, midi_clamp(velocity * 127)) 21 | midi_out.send_note(self._channel, pitch, 127) 22 | self._previous_pitch = pitch 23 | VolcaKick.note = note 24 | 25 | 26 | def note(self, pitch, velocity): 27 | if pitch == 36: 28 | velocity /= 3.0 29 | try: 30 | midi_out.send_control(self._channel, DRM.index(pitch - 36) + 40, midi_clamp(velocity * 127)) 31 | except ValueError: 32 | logger.warning("(warning: note doesn't exist)") 33 | midi_out.send_note(self._channel, pitch, 127) 34 | self._previous_pitch = pitch 35 | VolcaBeats.note = note 36 | 37 | 38 | def note(self, pitch, velocity): 39 | midi_out.send_control(self._channel, 19, midi_clamp(velocity * 127)) 40 | midi_out.send_note(self._channel, pitch, 127) 41 | self._previous_pitch = pitch 42 | VolcaDrum.note = note 43 | -------------------------------------------------------------------------------- /examples/20181009.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, os, math 4 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 5 | from braid import * 6 | 7 | 8 | Kicker = make( 9 | {'pitch': 64, 'envelope': 49, 'distortion': 50, 'sub': 51, 'body': 52, 'presence': 53, 'pan': 54, 'volume': 55}, 10 | {'pitch': 90, 'envelope': 127, 'distortion': 0, 'sub': 0, 'body': 127, 'presence': 127, 'pan': 64, 'volume': 64} 11 | ) 12 | 13 | def note(self, pitch, velocity): 14 | # midi_out.send_note(self._channel, self._previous_pitch, 0) 15 | midi_out.send_control(self._channel, 55, midi_clamp(velocity * 127)) 16 | midi_out.send_note(self._channel, pitch, 127) 17 | self._previous_pitch = pitch 18 | Kicker.note = note 19 | 20 | midi_out.throttle = 2/1000 21 | 22 | def pfix(p): 23 | assert p > 40 24 | p -= 41 25 | p *= 3 + 1/3 26 | p += 1/3 27 | p = math.floor(p) if p % 1 < .9 else math.ceil(p) 28 | return p 29 | 30 | def k(n=Bb2): 31 | def f(t): 32 | t.channel = 1 33 | t.pitch = 64 34 | t.pitch = pfix(n) 35 | t.envelope = 64 36 | t.distortion = 32 37 | t.sub = 115 38 | t.body = 127 39 | t.presence = 90 40 | t.velocity = 0.4 41 | return C1 42 | return f 43 | 44 | def s(t): 45 | t.channel = 2 46 | t.pitch = 64 47 | t.envelope = 127 48 | t.distortion = 0 49 | t.sub = 0 50 | t.body = 0 51 | t.presence = 127 52 | t.velocity = 1.0 53 | return C1 54 | 55 | def h(t): 56 | t.channel = 3 57 | t.pitch = 127 58 | t.envelope = 127 59 | t.distortion = 0 60 | t.sub = 0 61 | t.body = 127 62 | t.presence = 0 63 | t.velocity = 1.0 64 | return C1 65 | 66 | def hp(t): 67 | t.channel = 3 68 | t.pitch = 100 69 | t.envelope = 127 70 | t.distortion = 0 71 | t.sub = 0 72 | t.body = 127 73 | t.presence = 100 74 | t.velocity = 0.5 75 | return C1 76 | 77 | t1 = Kicker(1) 78 | t2 = Kicker(2) 79 | t3 = Kicker(3) 80 | t4 = Thread(4) 81 | 82 | tempo(120) 83 | t1.pattern = [k(), s, k(), k(), s, k(), (k(), ([k(), s])), (s, (s, [s, 0, 0, s]))] 84 | t2.pattern = [0, (h, [(h, 0), h])] * 4 85 | t3.pattern = hp, 0, s, 0 86 | t3.rate = 4/3 87 | 88 | play() 89 | -------------------------------------------------------------------------------- /examples/20181008.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, os, math 4 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 5 | from braid import * 6 | 7 | 8 | Kicker = make( 9 | {'pitch': 64, 'envelope': 49, 'distortion': 50, 'sub': 51, 'body': 52, 'presence': 53, 'pan': 54, 'volume': 55}, 10 | {'pitch': 90, 'envelope': 127, 'distortion': 0, 'sub': 0, 'body': 127, 'presence': 127, 'pan': 64, 'volume': 64} 11 | ) 12 | 13 | def note(self, pitch, velocity): 14 | # midi_out.send_note(self._channel, self._previous_pitch, 0) 15 | midi_out.send_control(self._channel, 55, midi_clamp(velocity * 127)) 16 | midi_out.send_note(self._channel, pitch, 127) 17 | self._previous_pitch = pitch 18 | Kicker.note = note 19 | 20 | midi_out.throttle = 2/1000 21 | 22 | def pfix(p): 23 | assert p > 40 24 | p -= 41 25 | p *= 3 + 1/3 26 | p += 1/3 27 | p = math.floor(p) if p % 1 < .9 else math.ceil(p) 28 | return p 29 | 30 | def k(n=Bb2): 31 | def f(t): 32 | t.channel = 1 33 | t.pitch = 64 34 | t.pitch = pfix(n) 35 | t.envelope = 64 36 | t.distortion = 32 37 | t.sub = 115 38 | t.body = 127 39 | t.presence = 90 40 | t.velocity = 0.4 41 | return C1 42 | return f 43 | 44 | def s(t): 45 | t.channel = 2 46 | t.pitch = 64 47 | t.envelope = 127 48 | t.distortion = 0 49 | t.sub = 0 50 | t.body = 0 51 | t.presence = 127 52 | t.velocity = 1.0 53 | return C1 54 | 55 | def h(t): 56 | t.channel = 3 57 | t.pitch = 127 58 | t.envelope = 127 59 | t.distortion = 0 60 | t.sub = 0 61 | t.body = 127 62 | t.presence = 0 63 | t.velocity = 1.0 64 | return C1 65 | 66 | def hp(t): 67 | t.channel = 3 68 | t.pitch = 100 69 | t.envelope = 127 70 | t.distortion = 0 71 | t.sub = 0 72 | t.body = 127 73 | t.presence = 100 74 | t.velocity = 0.5 75 | return C1 76 | 77 | t1 = Kicker(1) 78 | t2 = Kicker(2) 79 | t3 = Kicker(3) 80 | t4 = Thread(4) 81 | 82 | tempo(110) 83 | t1.pattern = [k(C2), 0, k(C2), h, (s, [s, 0, 0, s]), k(D2), 0, k(B1), s, h, k(B1), 0] 84 | t2.pattern = [0, (h, [hp, 0, hp]), 0, 0, (h, [hp, 0, hp]), 0, 0, (h, [hp, 0, hp])] 85 | t2.phase = 1/8 86 | # t3.pattern = [h, h] * 6 87 | 88 | play() 89 | -------------------------------------------------------------------------------- /examples/20181014.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, os, math 4 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 5 | from braid import * 6 | 7 | 8 | Kicker = make( 9 | {'pitch': 64, 'envelope': 49, 'distortion': 50, 'sub': 51, 'body': 52, 'presence': 53, 'pan': 54, 'volume': 55}, 10 | {'pitch': 90, 'envelope': 127, 'distortion': 0, 'sub': 0, 'body': 127, 'presence': 127, 'pan': 64, 'volume': 64} 11 | ) 12 | 13 | def note(self, pitch, velocity): 14 | # midi_out.send_note(self._channel, self._previous_pitch, 0) 15 | midi_out.send_control(self._channel, 55, midi_clamp(velocity * 127)) 16 | midi_out.send_note(self._channel, pitch, 127) 17 | self._previous_pitch = pitch 18 | Kicker.note = note 19 | 20 | midi_out.throttle = 2/1000 21 | 22 | def pfix(p): 23 | assert p > 40 24 | p -= 41 25 | p *= 3 + 1/3 26 | p += 1/3 27 | p = math.floor(p) if p % 1 < .9 else math.ceil(p) 28 | return p 29 | 30 | def k(n=Bb2): 31 | def f(t): 32 | t.channel = 1 33 | t.pitch = 64 34 | t.pitch = pfix(n) 35 | t.envelope = 64 36 | t.distortion = 32 37 | t.sub = 115 38 | t.body = 127 39 | t.presence = 90 40 | t.velocity = 0.4 41 | return C1 42 | return f 43 | 44 | def s(t): 45 | t.channel = 2 46 | t.pitch = 20 47 | t.envelope = 127 48 | t.distortion = 0 49 | t.sub = 0 50 | t.body = 0 51 | t.presence = 127 52 | t.velocity = 1.0 53 | return C1 54 | 55 | def h(t): 56 | t.channel = 3 57 | t.pitch = 127 58 | t.envelope = 127 59 | t.distortion = 0 60 | t.sub = 0 61 | t.body = 127 62 | t.presence = 0 63 | t.velocity = 1.0 64 | return C1 65 | 66 | def hp(t): 67 | t.channel = 3 68 | t.pitch = 100 69 | t.envelope = 127 70 | t.distortion = 0 71 | t.sub = 0 72 | t.body = 127 73 | t.presence = 100 74 | t.velocity = 0.5 75 | return C1 76 | 77 | t1 = Kicker(1) 78 | t2 = Kicker(2) 79 | t3 = Kicker(3) 80 | t4 = Thread(4) 81 | 82 | tempo(128) 83 | # tempo(90) 84 | 85 | # t1.pattern = [k(), 0, k(), [0, k()]] 86 | t1.pattern = [k(), k(), k(), k()] 87 | t2.pattern = [0, 0, [(h, 0), s], 0, 0, 0, s, 0] 88 | # t2.pattern = [0, s, 0, s, h, h, 0, s] 89 | # t2.phase = 1/8 90 | 91 | t3.pattern = [h, 0, (h, 0), h, 0, h, h, 0, h, 0, h, (h, 0), (0, h), h, (h, 0), 0] 92 | t3.micro = cross(8, 1.8) 93 | 94 | play() 95 | -------------------------------------------------------------------------------- /examples/20181012.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, os, math 4 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 5 | from braid import * 6 | 7 | 8 | Kicker = make( 9 | {'pitch': 64, 'envelope': 49, 'distortion': 50, 'sub': 51, 'body': 52, 'presence': 53, 'pan': 54, 'volume': 55}, 10 | {'pitch': 90, 'envelope': 127, 'distortion': 0, 'sub': 0, 'body': 127, 'presence': 127, 'pan': 64, 'volume': 64} 11 | ) 12 | 13 | def note(self, pitch, velocity): 14 | midi_out.send_control(self._channel, 55, midi_clamp(velocity * 127)) 15 | midi_out.send_note(self._channel, pitch, 127) 16 | self._previous_pitch = pitch 17 | Kicker.note = note 18 | 19 | midi_out.throttle = 2/1000 20 | 21 | def pfix(p): 22 | assert p > 40 23 | p -= 41 24 | p *= 3 + 1/3 25 | p += 1/3 26 | p = math.floor(p) if p % 1 < .9 else math.ceil(p) 27 | return p 28 | 29 | def k(n=C2): 30 | def f(t): 31 | t.channel = 1 32 | t.pitch = 64 33 | t.pitch = pfix(n) 34 | t.envelope = 64 35 | t.distortion = 32 36 | t.sub = 60 37 | t.body = 127 38 | t.presence = 90 39 | t.velocity = 0.3 40 | return C1 41 | return f 42 | 43 | def h(t): ## phaser off, exciter on 44 | t.channel = 2 45 | t.pitch = 64 46 | t.envelope = 30 47 | t.distortion = 0 48 | t.sub = 0 49 | t.body = 90 50 | t.presence = 0 51 | t.velocity = 1.0 52 | # t.channel = 2 53 | # t.pitch = 127 54 | # t.envelope = 0 55 | # t.distortion = 0 56 | # t.sub = 0 57 | # t.body = 0 58 | # t.presence = 127 59 | # t.velocity = 0.5 60 | return C1 61 | 62 | def s(t): 63 | t.channel = 3 64 | t.pitch = 64 65 | t.envelope = 127 66 | t.distortion = 127 67 | t.sub = 0 68 | t.body = 60 69 | t.presence = 80 70 | t.velocity = 0.75 71 | return C1 72 | 73 | def hp(t): 74 | t.channel = 3 75 | t.pitch = 100 76 | t.envelope = 127 77 | t.distortion = 0 78 | t.sub = 0 79 | t.body = 127 80 | t.presence = 100 81 | t.velocity = 0.5 82 | return C1 83 | 84 | t1 = Kicker(1) 85 | t2 = Kicker(2) 86 | t3 = Kicker(3) 87 | t4 = Thread(4) 88 | 89 | tempo(235) 90 | 91 | # t1.pattern = [[k(), [0, 0, (k(), 0)]], [(k(), 0), 0]] * 2 92 | t1.pattern = [k(), k()]#, 0, 0, (0, [0, 0, k()])] 93 | # t2.pattern = [0, h, 0, h, 0, h, 0, h] 94 | t2.pattern = 0, (h, [0, h]), 0, (h, [0, h]) 95 | t2.phase = 1/64 96 | # t3.pattern = 0, s, 0, s 97 | # t3.pattern = 0, 0, [0, (s, (s, [0, s]))], 0 98 | t3.pattern = 0, (0, (0, [s, s])), [0, (s, [0, s])], 0 99 | 100 | 101 | t1.micro = cross(3, 1.25) 102 | t2.micro = cross(3, 1.5) 103 | t3.micro = cross(3, 1.5) 104 | 105 | plot(t3.micro, 'red') 106 | plot(t2.micro, 'purple') 107 | show_plots() 108 | 109 | play() -------------------------------------------------------------------------------- /examples/20180804.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, os, math 4 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 5 | from braid import * 6 | 7 | Kicker = make( 8 | {'pitch': 64, 'envelope': 49, 'distortion': 50, 'sub': 51, 'body': 52, 'presence': 53, 'pan': 54, 'volume': 55}, 9 | {'pitch': 90, 'envelope': 127, 'distortion': 0, 'sub': 0, 'body': 127, 'presence': 127, 'pan': 64, 'volume': 64} 10 | ) 11 | 12 | def note(self, pitch, velocity): 13 | # midi_out.send_note(self._channel, self._previous_pitch, 0) 14 | midi_out.send_control(self._channel, 55, midi_clamp(velocity * 127)) 15 | midi_out.send_note(self._channel, pitch, 127) 16 | self._previous_pitch = pitch 17 | Kicker.note = note 18 | 19 | 20 | def k(t): 21 | t.pitch = 64 22 | t.body = 127 23 | t.presence = 127 24 | t.envelope = 64 25 | t.sub = 0 26 | t.distortion = 0 27 | t.velocity = 0.25 28 | return C1 29 | 30 | def kg(t): 31 | t.pitch = 64 32 | t.body = 127 33 | t.presence = 80 34 | t.envelope = 64 35 | t.sub = 0 36 | t.distortion = 0 37 | t.velocity = 1/8 38 | return C1 39 | 40 | def s(t): 41 | t.pitch = 64 42 | t.body = 0 43 | t.presence = 127 44 | t.envelope = 127 45 | t.sub = 0 46 | t.distortion = 0 47 | t.velocity = 1.0 48 | return C1 49 | 50 | def sg(t): 51 | t.pitch = 64 52 | t.body = 0 53 | t.presence = 80 54 | t.envelope = 127 55 | t.sub = 0 56 | t.distortion = 0 57 | t.velocity = 0.5 58 | return C1 59 | 60 | def h(t): 61 | t.pitch = 64 62 | t.body = 0 63 | t.presence = 0 64 | t.envelope = 127 65 | t.sub = 0 66 | t.distortion = 0 67 | t.velocity = 1.0 68 | return C1 69 | 70 | t1 = Kicker(1) 71 | t1.start() 72 | 73 | t2 = Kicker(2) 74 | t2.start() 75 | 76 | t3 = Kicker(3) 77 | t3.start() 78 | 79 | midi_out.throttle = 2/1000 80 | # tempo(118) 81 | tempo(190) # ha! jungle mode! 82 | 83 | t1.add('seq') 84 | t1.add('i') 85 | t1.seq = [Bb2, Bb2, Ab2, Ab2] 86 | t1.i = 0 87 | 88 | 89 | def pfix(p): 90 | p -= 41 91 | p *= 3 + 1/3 92 | p += 1/3 93 | p = math.floor(p) if p % 1 < .9 else math.ceil(p) 94 | return p 95 | 96 | def k(t): 97 | t.pitch = pfix(t.seq[t.i % len(t.seq)]) 98 | t.i += 1 99 | t.body = 127 100 | t.presence = 90 101 | # t.envelope = 64 102 | t.sub = 115 103 | t.distortion = 32 104 | t.velocity = 0.25 105 | return C1 106 | 107 | # t1.pattern = [k, [h, h], k, [(0, k), (h, [h, h])], k, k], [[h, (h, [h, h])], k, [0, (h, k)], k, k, 0] 108 | t1.pattern = [k, h, k, [(0, k), h], k, k], [h, k, [0, (h, k)], k, k, 0] 109 | t1.rate = 1/2 110 | 111 | t2.pattern = [(s, [s, s]), h, (s, [s, s]), h, (s, [s, s])] 112 | t2.rate = 6/5 113 | 114 | # t3.pattern = [h, h, h] * 4 115 | 116 | play() 117 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | CHANGELOG 2 | ========= 3 | 4 | ## v0.14.1 5 | - fixed distribution issue causing circular import error 6 | 7 | ## v0.14.0 8 | Additions from github user discohead: 9 | - Note "queues" for Patterns which return a rotating value each cycle: e.g. Q([1, 2, 3]) first returns 1, then 2 on the next cycle, 3 on the next, then 1 again and so on. With the option to randomize the rotation direction via a drunk property, e.g. Q([1, 2, 3], drunk=True). 10 | - Per note velocity scaling from float steps, e.g. 60.5 will play note 60 at velocity * 0.5, if the part after the decimal is .0 fallback to existing grace note behavior 11 | - A v() for generating notes with velocity scaling from named (or not) notes, options for randomizing the velocity scaling 12 | - A s() for generating notes with velocity scaling using signals driven by the thread's phase 13 | - A sh() tween generator for making random, sample and hold like tweens, with lock and lag functionality. 14 | - sin(), tri(), pw() tween generators and associated signal functions 15 | - A phase_offset property for tweens. 16 | - A number of new signals likes noise(), triangle(), pulse(), sine() 17 | - Signals have (a)mp, (r)ate, (p)hase and (b)ias parameters and can be composed of other signals, i.e.: sine(a=sine(p=triangle(s=pulse(r=4), r=2))) 18 | - A number of additional parameters to the euc() pattern generator 19 | - A constrain property to Scales to keep degrees in range and avoid ScaleErrors 20 | - An octaves_above property to Scales for customizing the upper octave boundary 21 | - A quantize() method to Scales for quantizing semitone values to the scale 22 | - A notes() method to Patterns for getting all non-0, non-REST values in a Pattern 23 | - An invert() method to Patterns, e.g. [1, 0, 1, 0] becomes [0, 1, 0, 1] (but with some options for customization) 24 | - A drunk property on Pattern to treat all Qs as drunk 25 | - A tweenable transpose property to Threads. This property can also be a list of values that rotates at a rate determined by the transpose_step_len property, which determines how many steps to hold the transpose value before advancing to the next. Markov-expansion of tuples are supported. 26 | - Convenience methods on Thread for getting setting the root and scale of its chord 27 | - Some additional named Scales 28 | 29 | ## v0.13.0 30 | - channel now a changeable parameter 31 | - control values cached per-channel-per-thread 32 | - start now called automatically when not livecoding 33 | - new signal syntax 34 | - cross timing emphasis 35 | - cleaned up documentation 36 | - bugfixes 37 | 38 | ## v0.12.0 39 | - fixed note-level control change so it fires a priori 40 | - fixed issues 7-10 41 | - changed notation octaves to MIDI standard instead of traditional 42 | - added saw feature 43 | 44 | ## v0.11.0 45 | - improved error handling 46 | - added osc feature 47 | - added 'keyboard' setting 48 | - added MidiIn->Thread capability 49 | - added breakpoint signals 50 | 51 | ## v0.10.1 52 | - refactored to eliminate lib folder 53 | - added on_end to Tween 54 | - realized IDLE is a good host 55 | 56 | ## v0.10.0 57 | - made a changelog 58 | - eliminated returns for in-place pattern methods (to suppress terminal output) 59 | - added repeat functionality to Thread and core 60 | - documentation 61 | -------------------------------------------------------------------------------- /braid/synths.yaml: -------------------------------------------------------------------------------- 1 | Meeblip: 2 | controls: 3 | filter_resonance: 48 4 | filter_cutoff: 49 5 | lfo_frequency: 50 6 | lfo_level: 51 7 | filter_env: 52 8 | portamento: 53 9 | pulse_width: 54 10 | detune: 55 11 | filter_decay: 58 12 | filter_attack: 59 13 | amp_decay: 60 14 | amp_attack: 61 15 | fm: 65 16 | lfo_random: 66 17 | lfo_wave: 67 18 | filter_mode: 68 19 | distortion: 69 20 | lfo_enable: 70 21 | lfo_destination: 71 22 | anti_alias: 72 23 | osc_octave: 73 24 | osc_enable: 74 25 | osc_wave: 75 26 | sustain: 76 27 | osc_noise: 77 28 | pwm_sweep: 78 29 | wave: 79 30 | defaults: 31 | filter_resonance: 64 32 | filter_cutoff: 64 33 | lfo_frequency: 64 34 | lfo_level: 64 35 | filter_env: 64 36 | portamento: 64 37 | pulse_width: 64 38 | detune: 64 39 | filter_decay: 64 40 | filter_attack: 0 41 | amp_decay: 64 42 | amp_attack: 0 43 | fm: 0 44 | lfo_random: 0 45 | lfo_wave: 0 46 | filter_mode: 0 47 | distortion: 127 48 | lfo_enable: 0 49 | lfo_destination: 0 50 | anti_alias: 0 51 | osc_octave: 127 52 | osc_enable: 127 53 | osc_wave: 127 54 | sustain: 0 55 | osc_noise: 0 56 | pwm_sweep: 0 57 | wave: 0 58 | 59 | Anode: 60 | controls: 61 | attack: 54 62 | decay: 53 63 | filter_cutoff: 52 64 | pulse_width: 51 65 | osc_detune: 50 66 | lfo_rate: 49 67 | lfo_depth: 48 68 | glide: 55 69 | vcf_envelope: 56 70 | sustain: 64 71 | octave: 65 72 | sweep: 66 73 | lfo_destination: 67 74 | lfo_random: 68 75 | osc_wave: 70 76 | defaults: 77 | attack: 0 78 | decay: 0 79 | filter_cutoff: 64 80 | pulse_width: 64 81 | osc_detune: 64 82 | lfo_rate: 0 83 | lfo_depth: 0 84 | glide: 0 85 | vcf_envelope: 0 86 | sustain: 127 87 | octave: 0 88 | sweep: 127 89 | lfo_destination: 0 90 | lfo_random: 0 91 | osc_wave: 127 92 | 93 | Triode: 94 | controls: 95 | lfo_depth: 48 96 | lfo_rate: 49 97 | detune: 50 98 | glide: 51 99 | attack: 60 100 | decay: 55 101 | filter_res: 52 102 | filter_cutoff: 53 103 | filter_attack: 59 104 | filter_decay: 54 105 | filter_accent: 56 106 | filter_mod: 57 107 | pulse_width: 58 108 | sustain: 64 109 | sub: 65 110 | pwm_sweep: 66 111 | osc: 68 112 | lfo_dest: 67 113 | lfo_randomize: 69 114 | lfo_retrigger: 70 115 | defaults: 116 | lfo_depth: 0 117 | lfo_rate: 0 118 | detune: 64 119 | glide: 0 120 | attack: 0 121 | decay: 0 122 | filter_res: 64 123 | filter_cutoff: 127 124 | filter_attack: 0 125 | filter_decay: 0 126 | filter_accent: 127 127 | filter_mod: 127 128 | pulse_width: 64 129 | sustain: 127 130 | sub: 127 131 | pwm_sweep: 127 132 | osc: 127 133 | lfo_dest: 127 134 | lfo_randomize: 0 135 | lfo_retrigger: 127 136 | 137 | VolcaBeats: 138 | controls: 139 | clap_pcm: 50 140 | claves_pcm: 51 141 | agogo_pcm: 52 142 | crash_pcm: 53 143 | stutter_time: 54 144 | stutter_depth: 55 145 | tom_decay: 56 146 | closed_hat_decay: 57 147 | open_hat_decay: 58 148 | hat_grain: 59 149 | defaults: 150 | clap_pcm: 127 151 | claves_pcm: 127 152 | agogo_pcm: 127 153 | crash_pcm: 127 154 | stutter_time: 0 155 | stutter_depth: 0 156 | tom_decay: 127 157 | closed_hat_decay: 50 158 | open_hat_decay: 64 159 | hat_grain: 127 160 | 161 | VolcaKick: 162 | controls: 163 | pulse_colour: 40 164 | pulse_level: 41 165 | amp_attack: 42 166 | amp_decay: 43 167 | drive: 44 168 | tone: 45 169 | resonator_pitch: 46 170 | resonator_bend: 47 171 | resonator_time: 48 172 | accent: 49 173 | defaults: 174 | None 175 | 176 | VolcaDrum: 177 | controls: 178 | pan: 10 179 | select_1: 14 180 | select_2: 15 181 | select: 16 182 | attack_1: 20 183 | attack_2: 21 184 | attack: 22 185 | release_1: 23 186 | release_2: 24 187 | release: 25 188 | pitch_1: 26 189 | pitch_2: 27 190 | pitch: 28 191 | mod_1: 29 192 | mod_2: 30 193 | mod: 31 194 | mod_rate_1: 46 195 | mod_rate_2: 47 196 | mod_rate: 48 197 | bit: 49 198 | fold: 50 199 | drive: 51 200 | gain: 52 201 | wave_send: 103 202 | wave_model: 116 203 | wave_decay: 117 204 | wave_body: 118 205 | wave_tune: 119 206 | defaults: 207 | pan: 64 208 | level: 127 209 | pitch: 64 210 | gain: 64 211 | 212 | MBase: 213 | controls: 214 | tune: 100 215 | pitch: 101 216 | decay: 102 217 | harmonics: 103 218 | pulse: 104 219 | noise: 105 220 | attack: 106 221 | eq: 107 222 | compression: 113 223 | gate_time: 114 224 | metal_noise: 115 225 | volume: 117 226 | lfo_sync: 120 227 | lfo_one_shot: 123 228 | lfo_intensity: 121 229 | lfo_rate: 122 230 | defaults: 231 | tune: 127 232 | pitch: 64 233 | decay: 25 234 | harmonics: 64 235 | pulse: 127 236 | noise: 127 237 | attack: 0 238 | eq: 0 239 | compression: 40 240 | gate_time: 32 241 | metal_noise: 127 242 | volume: 255 ## scales note velocity 243 | lfo_sync: 0 244 | lfo_one_shot: 0 245 | lfo_intensity: 127 246 | lfo_rate: 0 247 | -------------------------------------------------------------------------------- /braid/core.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, time, threading, queue, __main__, atexit 4 | from .midi import midi_in 5 | from .logger import logger 6 | 7 | LIVECODING = not hasattr(__main__, "__file__") 8 | 9 | class Driver(threading.Thread): 10 | 11 | def __init__(self): 12 | super(Driver, self).__init__() 13 | self.daemon = True 14 | self.threads = [] 15 | self.grain = 0.01 16 | self.t = 0.0 17 | self.rate = 1.0 18 | self.previous_t = 0.0 19 | self.previous_cycles = 0 20 | self.running = False 21 | self._cycles = 0.0 22 | self._triggers = [] 23 | 24 | def start(self): 25 | super(Driver, self).start() 26 | logger.info("-------------> O") 27 | if not LIVECODING: 28 | try: 29 | while self.running: 30 | time.sleep(0.1) 31 | except KeyboardInterrupt: 32 | driver.stop() 33 | 34 | def run(self): 35 | self.start_t = time.time() 36 | while True: 37 | self.t = time.time() - self.start_t 38 | if self.running: 39 | try: 40 | if not self.running: 41 | break 42 | midi_in.perform_callbacks() 43 | delta_t = self.t - self.previous_t 44 | self._cycles += delta_t * self.rate 45 | if int(self._cycles) != self.previous_cycles: 46 | self.update_triggers() 47 | self.previous_cycles = int(self._cycles) 48 | for thread in self.threads: 49 | c = time.time() 50 | try: 51 | thread.update(delta_t) 52 | except Exception as e: 53 | logger.error("\n[Error: \"%s\"]" % e) 54 | thread.stop() 55 | raise e 56 | rc = int((time.time() - c) * 1000) 57 | if rc > 1: 58 | logger.warning("[Warning: update took %dms]\n>>> " % rc, end='') 59 | except KeyboardInterrupt: 60 | self.stop() 61 | elif not LIVECODING: 62 | break 63 | self.previous_t = self.t 64 | time.sleep(self.grain) 65 | 66 | def trigger(self, f=None, cycles=0, repeat=0): 67 | if f is None and repeat is False: 68 | self._triggers = [trigger for trigger in self._triggers if trigger[2] is not True] # filter repeat=True 69 | elif f is False: 70 | self._triggers = [] 71 | else: 72 | try: 73 | assert(callable(f)) 74 | if cycles == 0: 75 | assert repeat == 0 76 | except AssertionError as e: 77 | logger.error("\n[Bad arguments for trigger]") 78 | else: 79 | self._triggers.append([f, cycles, repeat, 0]) # last parameter is cycle edges so far 80 | 81 | def update_triggers(self): 82 | """Check trigger functions a fire as necessary""" 83 | updated = False 84 | for t, trigger in enumerate(self._triggers): 85 | trigger[3] += 1 # increment edge 86 | if trigger[1] - trigger[3] == 0: 87 | try: 88 | trigger[0]() 89 | except Exception as e: 90 | logger.error("\n[Error: %s]" % e) 91 | if trigger[2] is True: 92 | self.trigger(trigger[0], trigger[1], True) # create new trigger with same properties 93 | else: 94 | trigger[2] -= 1 95 | if trigger[2] > 0: 96 | logger.info("\n[Made new trigger with %s]" % trigger[2]) 97 | self.trigger(trigger[0], trigger[1], trigger[2] - 1) # same, but decrement repeats 98 | self._triggers[t] = None # clear this trigger 99 | updated = True 100 | if updated: 101 | self._triggers = [trigger for trigger in self._triggers if trigger is not None] 102 | 103 | def stop(self): 104 | self.running = False 105 | for thread in self.threads: 106 | if thread._running: 107 | thread.stop() 108 | 109 | def tempo(value=False): 110 | """Convert to a multiplier of 1hz cycles""" 111 | if value: 112 | value /= 60.0 113 | value /= 4.0 114 | driver.rate = value 115 | else: 116 | return driver.rate * 4.0 * 60.0 117 | 118 | def rate(value=False): 119 | """Cycles in hz""" 120 | if value: 121 | driver.rate = value 122 | else: 123 | return driver.rate 124 | 125 | def play(): 126 | driver.running = True 127 | if not driver.is_alive(): 128 | driver.start() 129 | logger.info("[Playing]") 130 | 131 | def pause(): 132 | driver.running = False 133 | for thread in driver.threads: 134 | thread.end() 135 | logger.info("[Paused]") 136 | 137 | def stop(): 138 | driver.stop() 139 | logger.info("[Stopped]") 140 | 141 | def clear(): 142 | for thread in driver.threads: 143 | if thread._running: 144 | thread.stop() 145 | logger.info("[Cleared]") 146 | 147 | def exit_handler(): 148 | driver.stop() 149 | time.sleep(0.1) # for midi to finish 150 | logger.info("\n-------------> X") 151 | atexit.register(exit_handler) 152 | 153 | driver = Driver() 154 | trigger = driver.trigger 155 | 156 | tempo(115) 157 | 158 | -------------------------------------------------------------------------------- /braid/midi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import sys, time, threading, atexit, queue, rtmidi 4 | from rtmidi.midiconstants import NOTE_ON, NOTE_OFF, CONTROLLER_CHANGE 5 | from . import num_args 6 | from .logger import logger 7 | 8 | log_midi = False 9 | 10 | class MidiOut(threading.Thread): 11 | 12 | def __init__(self, interface=0, throttle=0): 13 | threading.Thread.__init__(self) 14 | self.daemon = True 15 | self._interface = interface 16 | self.throttle = throttle 17 | self.queue = queue.Queue() 18 | self.midi = rtmidi.MidiOut() 19 | available_interfaces = self.scan() 20 | if available_interfaces: 21 | if self._interface >= len(available_interfaces): 22 | logger.info("Interface index %s not available" % self._interface) 23 | return 24 | logger.info("MIDI OUT: %s" % available_interfaces[self._interface]) 25 | self.midi.open_port(self._interface) 26 | else: 27 | logger.info("MIDI OUT opening virtual interface 'Braid'...") 28 | self.midi.open_virtual_port('Braid') 29 | self.start() 30 | 31 | def scan(self): 32 | available_interfaces = self.midi.get_ports() 33 | if len(available_interfaces): 34 | logger.info("MIDI outputs available: %s" % available_interfaces) 35 | else: 36 | logger.info("No MIDI outputs available") 37 | return available_interfaces 38 | 39 | def send_control(self, channel, control, value): 40 | self.queue.put((channel, (control, value), None)) 41 | 42 | def send_note(self, channel, pitch, velocity): 43 | self.queue.put((channel, None, (pitch, velocity))) 44 | 45 | @property 46 | def interface(self): 47 | return self._interface 48 | 49 | @interface.setter 50 | def interface(self, interface): 51 | self.__init__(interface=interface, throttle=self.throttle) 52 | 53 | def run(self): 54 | while True: 55 | channel, control, note = self.queue.get() 56 | if control is not None: 57 | control, value = control 58 | if type(value) == bool: 59 | value = 127 if value else 0 60 | if log_midi: 61 | logger.info("MIDI ctrl %s %s %s" % (channel, control, value)) 62 | channel -= 1 63 | self.midi.send_message([CONTROLLER_CHANGE | (channel & 0xF), control, value]) 64 | if note is not None: 65 | pitch, velocity = note 66 | if log_midi: 67 | logger.info("MIDI note %s %s %s" % (channel, pitch, velocity)) 68 | channel -= 1 69 | if velocity: 70 | self.midi.send_message([NOTE_ON | (channel & 0xF), pitch & 0x7F, velocity & 0x7F]) 71 | else: 72 | self.midi.send_message([NOTE_OFF | (channel & 0xF), pitch & 0x7F, 0]) 73 | if self.throttle > 0: 74 | time.sleep(self.throttle) 75 | 76 | 77 | class MidiIn(threading.Thread): 78 | 79 | def __init__(self, interface=0): 80 | threading.Thread.__init__(self) 81 | self.daemon = True 82 | self._interface = interface 83 | self.queue = queue.Queue() 84 | self.midi = rtmidi.MidiIn() 85 | self.callbacks = {} 86 | self.threads = [] 87 | available_interfaces = self.scan() 88 | if available_interfaces: 89 | if self._interface >= len(available_interfaces): 90 | logger.info("Interface index %s not available" % self._interface) 91 | return 92 | logger.info("MIDI IN: %s" % available_interfaces[self._interface]) 93 | self.midi.open_port(self._interface) 94 | self.start() 95 | 96 | def scan(self): 97 | available_interfaces = self.midi.get_ports() 98 | if 'Braid' in available_interfaces: 99 | available_interfaces.remove('Braid') 100 | if len(available_interfaces): 101 | logger.info("MIDI inputs available: %s" % available_interfaces) 102 | else: 103 | logger.info("No MIDI inputs available") 104 | return available_interfaces 105 | 106 | @property 107 | def interface(self): 108 | return self._interface 109 | 110 | @interface.setter 111 | def interface(self, interface): 112 | self.__init__(interface=interface) 113 | 114 | def run(self): 115 | def receive_message(event, data=None): 116 | message, deltatime = event 117 | if message[0] & 0b11110000 == CONTROLLER_CHANGE: 118 | nop, control, value = message 119 | self.queue.put((control, value / 127.0)) 120 | elif (message[0] & 0b11110000 == NOTE_ON): 121 | if len(message) < 3: 122 | return ## ? 123 | channel, pitch, velocity = message 124 | channel -= NOTE_ON 125 | if channel < len(self.threads): 126 | thread = self.threads[channel] 127 | thread.note(pitch, velocity) 128 | self.midi.set_callback(receive_message) 129 | while True: 130 | time.sleep(0.1) 131 | 132 | def perform_callbacks(self): 133 | while True: 134 | try: 135 | control, value = self.queue.get_nowait() 136 | except queue.Empty: 137 | return 138 | if control in self.callbacks: 139 | if num_args(self.callbacks[control]) > 0: 140 | self.callbacks[control](value) 141 | else: 142 | self.callbacks[control]() 143 | 144 | 145 | def callback(self, control, f): 146 | """For a given control message, call a function""" 147 | self.callbacks[control] = f 148 | 149 | 150 | midi_out = MidiOut(0) 151 | midi_in = MidiIn(0) 152 | time.sleep(0.5) 153 | logger.info("MIDI ready") 154 | -------------------------------------------------------------------------------- /docs/page.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Braid MIDI sequencer 6 | 7 | 8 | 9 | 10 | 12 | 13 | 14 | 15 | 16 | 17 | 116 | 117 | 118 |
119 | 120 | CONTENT 121 | 122 |
123 | 124 | -------------------------------------------------------------------------------- /braid/signal.py: -------------------------------------------------------------------------------- 1 | import time, math, __main__ 2 | from random import random, triangular, uniform 3 | 4 | 5 | def calc_pos(pos, rate, phase): 6 | pos = clamp(pos) 7 | pos = pos * rate(pos) if callable(rate) else pos * rate 8 | return (pos + phase(pos)) % 1.0 if callable(phase) else (pos + phase) % 1.0 9 | 10 | 11 | def amp_bias(value, amp, bias, pos=None): 12 | p = value if pos is None else pos 13 | amp = amp(p) if callable(amp) else amp 14 | bias = bias(p) if callable(bias) else bias 15 | return value * amp + bias 16 | 17 | 18 | def pos2rad(pos): 19 | pos = clamp(pos) 20 | degrees = pos * 360 21 | return math.radians(degrees) 22 | 23 | 24 | def clamp(pos): 25 | if pos > 1.0: 26 | return 1.0 27 | elif pos < 0.0: 28 | return 0.0 29 | else: 30 | return pos 31 | 32 | 33 | def const(value, mod=False, a=1, r=1, p=0, b=0): 34 | def f(pos): 35 | if mod: 36 | pos = calc_pos(pos, r, p) 37 | v = value(pos) if callable(value) else value 38 | return amp_bias(v, a, b, pos) 39 | else: 40 | return value 41 | 42 | return f 43 | 44 | 45 | def noise(l=0, h=1, a=1, r=1, p=0, b=0, m=None): 46 | def f(pos): 47 | pos = calc_pos(pos, r, p) 48 | lo = l(pos) if callable(l) else l 49 | hi = h(pos) if callable(h) else h 50 | if m is not None: 51 | mode = m(pos) if callable(m) else m 52 | return amp_bias(triangular(lo, hi, mode), a, b, pos) 53 | else: 54 | return amp_bias(uniform(lo, hi), a, b, pos) 55 | 56 | return f 57 | 58 | 59 | def linear(a=1, r=1, p=0, b=0): 60 | def f(pos): 61 | pos = calc_pos(pos, r, p) 62 | return amp_bias(pos, a, b) 63 | 64 | return f 65 | 66 | 67 | def inverse_linear(a=1, r=1, p=0, b=0): 68 | def f(pos): 69 | pos = calc_pos(1 - pos, r, p) 70 | return amp_bias(pos, a, b) 71 | 72 | return f 73 | 74 | 75 | def triangle(s=.5, a=1, r=1, p=0, b=0): 76 | def f(pos): 77 | pos = calc_pos(pos, r, p) 78 | sym = s(pos) if callable(s) else s 79 | if pos < sym: 80 | value = pos * 1 / sym 81 | else: 82 | value = 1 - ((pos - sym) * (1 / (1 - sym))) 83 | return amp_bias(value, a, b, pos) 84 | 85 | return f 86 | 87 | 88 | def pulse(w=.5, a=1, r=1, p=0, b=0): 89 | def f(pos): 90 | pos = calc_pos(pos, r, p) 91 | width = w(pos) if callable(w) else w 92 | if pos < width: 93 | return amp_bias(0.0, a, b, pos) 94 | else: 95 | return amp_bias(1.0, a, b, pos) 96 | 97 | return f 98 | 99 | 100 | def ease_in(exp=2, a=1, r=1, p=0, b=0): 101 | def f(pos): 102 | pos = calc_pos(pos, r, p) 103 | e = exp(pos) if callable(exp) else exp 104 | return amp_bias(pos ** e, a, b, pos) 105 | 106 | return f 107 | 108 | 109 | def ease_out(exp=3, a=1, r=1, p=0, b=0): 110 | def f(pos): 111 | pos = calc_pos(pos, r, p) 112 | e = exp(pos) if callable(exp) else exp 113 | return amp_bias(((pos - 1) ** e + 1), a, b, pos) 114 | 115 | return f 116 | 117 | 118 | def ease_in_out(exp=3, a=1, r=1, p=0, b=0): 119 | def f(pos): 120 | pos = calc_pos(pos, r, p) 121 | value = pos * 2 122 | e = exp(pos) if callable(exp) else exp 123 | if value < 1: 124 | return amp_bias(0.5 * value ** e, a, b, pos) 125 | value -= 2 126 | return amp_bias(0.5 * (value ** e + 2), a, b, pos) 127 | 128 | return f 129 | 130 | 131 | def ease_out_in(exp=3, a=1, r=1, p=0, b=0): 132 | def f(pos): 133 | pos = calc_pos(pos, r, p) 134 | value = pos * 2 - 1 135 | e = exp(pos) if callable(exp) else exp 136 | if value < 2: 137 | return amp_bias(0.5 * value ** e + 0.5, a, b, pos) 138 | else: 139 | return amp_bias(1.0 - (0.5 * value ** e + 0.5), a, b, pos) 140 | 141 | return f 142 | 143 | 144 | def sine(a=1, r=1, p=0, b=0): 145 | def f(pos): 146 | pos = calc_pos(pos, r, p) 147 | return amp_bias(math.sin(pos2rad(pos)) * 0.5 + 0.5, a, b, pos) 148 | 149 | return f 150 | 151 | 152 | def normalize(signal): 153 | min_value = min(signal) 154 | max_value = max(signal) 155 | return [(v - min_value) / (max_value - min_value) for v in signal] 156 | 157 | 158 | def timeseries(timeseries): 159 | timeseries = normalize(timeseries) 160 | 161 | def f(pos): 162 | indexf = pos * (len(timeseries) - 1) 163 | pos = indexf % 1.0 164 | value = (timeseries[math.floor(indexf)] * (1.0 - pos)) + (timeseries[math.ceil(indexf)] * pos) 165 | return value 166 | 167 | return f 168 | 169 | 170 | def breakpoints(*breakpoints): 171 | """ eg: 172 | breakpoints( [0, 0], 173 | [2, 1, linear()], 174 | [6, 2, ease_out()], 175 | [7, 0], 176 | [12, 3, ease_in()], 177 | [14, 2, ease_out()], 178 | [15, 0, ease_in_out()] 179 | ) 180 | """ 181 | min_x = min(breakpoints, key=lambda bp: bp[0])[0] 182 | domain = max(breakpoints, key=lambda bp: bp[0])[0] - min_x 183 | min_y = min(breakpoints, key=lambda bp: bp[1])[1] 184 | resolution = max(breakpoints, key=lambda bp: bp[1])[1] - min_y 185 | breakpoints = [ 186 | [(bp[0] - min_x) / float(domain), (bp[1] - min_y) / float(resolution), None if not len(bp) == 3 else bp[2]] for 187 | bp in breakpoints] 188 | 189 | def f(pos): 190 | index = 0 191 | while index < len(breakpoints) and breakpoints[index][0] < pos: 192 | index += 1 193 | if index == 0: 194 | return breakpoints[index][1] 195 | if index == len(breakpoints): 196 | return breakpoints[-1][1] 197 | start_point, end_point = breakpoints[index - 1], breakpoints[index] 198 | if end_point[2] is None: 199 | return start_point[1] 200 | pos = (pos - start_point[0]) / (end_point[0] - start_point[0]) 201 | if end_point[2] is not linear: 202 | pos = end_point[2](pos) 203 | return start_point[1] + (pos * (end_point[1] - start_point[1])) 204 | 205 | return f 206 | 207 | 208 | def cross(division, degree): 209 | bps = [[0, 0]] 210 | for d in range(division): 211 | d += 1 212 | bps.append([d, d / division, ease_in(degree)]) 213 | f = breakpoints(*bps) 214 | return f 215 | 216 | 217 | class Plotter(): 218 | instance = None 219 | 220 | def __init__(self): 221 | import tkinter 222 | self.master = tkinter.Tk() 223 | self.width, self.height = 1000, 250 224 | self.margin = 20 225 | self.w = tkinter.Canvas(self.master, width=self.width + self.margin * 2, height=self.height + self.margin * 2) 226 | self.w.pack() 227 | self.w.create_rectangle(self.margin - 1, self.margin - 1, self.width + self.margin + 1, 228 | self.height + self.margin + 1) 229 | 230 | @classmethod 231 | def plot(cls, bp_f, color="red"): 232 | if not hasattr(__main__, "__file__") or cls.instance is None: 233 | cls.instance = Plotter() 234 | points = [(i + cls.instance.margin, 235 | ((1.0 - bp_f(float(i) / cls.instance.width)) * cls.instance.height) + cls.instance.margin) for i in 236 | range(int(cls.instance.width))] 237 | cls.instance.w.create_line(points, fill=color, width=2.0) 238 | 239 | @classmethod 240 | def show_plots(cls): 241 | if cls.instance is not None: 242 | cls.instance.master.update() 243 | 244 | 245 | def plot(signal, color="red"): 246 | Plotter.plot(signal, color) 247 | 248 | 249 | def show_plots(): 250 | Plotter.show_plots() 251 | -------------------------------------------------------------------------------- /braid/notation.py: -------------------------------------------------------------------------------- 1 | from random import randint, choice, random, shuffle, uniform 2 | from collections import deque 3 | from bisect import bisect_left 4 | from .signal import amp_bias, calc_pos 5 | 6 | 7 | class Scale(list): 8 | """Allows for specifying scales by degree, up to 1 octave below and octaves_above above (default 2)""" 9 | """Set constrain=True to octave shift out-of-range degrees into range, preserving pitch class, else ScaleError""" 10 | """Any number of scale steps is supported, but default for MAJ: """ 11 | """ -1, -2, -3, -4, -5, -6, -7, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14""" 12 | 13 | def __init__(self, *args, constrain=False, octaves_above=2): 14 | self.constrain = constrain 15 | self.octaves_above = octaves_above 16 | super(Scale, self).__init__(*args) 17 | 18 | def __getitem__(self, degree): 19 | grace = False 20 | if type(degree) == float: 21 | degree = int(degree) 22 | grace = True 23 | if not ((type(degree) == int or degree == R) and degree != 0): 24 | raise ScaleError(degree) 25 | octave_shift = 0 26 | if degree == R: 27 | degree = list.__getitem__(self, randint(0, len(self) - 1)) 28 | if self.constrain: 29 | while degree > self._upper_bound(): 30 | degree = degree - len(self) 31 | while degree < 0 - len(self): 32 | degree = degree + len(self) 33 | else: 34 | if degree > self._upper_bound() or degree < 0 - len(self): 35 | raise ScaleError(degree) 36 | if degree < 0: 37 | degree = abs(degree) 38 | octave_shift -= 12 39 | if degree > len(self): 40 | octave_shift += ((degree - 1) // len(self)) * 12 41 | degree = ((degree - 1) % len(self)) + 1 42 | semitone = super(Scale, self).__getitem__(degree - 1) 43 | semitone += octave_shift 44 | if grace: 45 | return float(semitone) 46 | return semitone 47 | 48 | def _upper_bound(self): 49 | return len(self) * self.octaves_above 50 | 51 | def rotate(self, steps): 52 | l = list(self) 53 | scale = l[steps:] + l[:steps] 54 | scale = [degree - scale[0] for degree in scale] 55 | scale = [(degree + 12) if degree < 0 else degree for degree in scale] 56 | return Scale(scale) 57 | 58 | def quantize(self, interval): 59 | """Quantize a semitone interval to the scale, negative and positive intervals are accepted without bounds""" 60 | """Intervals not in the scale are shifted up in pitch to the nearest interval in the scale""" 61 | """i.e. for MAJ, 1 returns 2, 3 returns 4, -2 returns -1, -4 returns -3, etc...""" 62 | if interval in self: 63 | return interval 64 | octave_shift = (interval // 12) * 12 65 | interval = interval - octave_shift 66 | degree = bisect_left(list(self), interval) + 1 67 | return self[degree] + octave_shift 68 | 69 | 70 | class ScaleError(Exception): 71 | 72 | def __init__(self, degree): 73 | self.degree = degree 74 | 75 | def __str__(self): 76 | return repr("Illegal scale degree '%s'" % self.degree) 77 | 78 | 79 | K = 36 80 | S = 38 81 | H = 42 82 | O = 46 83 | 84 | CN = 12 85 | DbN = 13 86 | DN = 14 87 | EbN = 15 88 | EN = 16 89 | FN = 17 90 | GbN = 18 91 | GN = 19 92 | AbN = 20 93 | AN = 21 94 | BbN = 22 95 | BN = 23 96 | 97 | C0 = 24 98 | Db0 = 25 99 | D0 = 26 100 | Eb0 = 27 101 | E0 = 28 102 | F0 = 29 103 | Gb0 = 30 104 | G0 = 31 105 | Ab0 = 32 106 | A0 = 33 107 | Bb0 = 34 108 | B0 = 35 109 | 110 | C1 = 36 111 | Db1 = 37 112 | D1 = 38 113 | Eb1 = 39 114 | E1 = 40 115 | F1 = 41 116 | Gb1 = 42 117 | G1 = 43 118 | Ab1 = 44 119 | A1 = 45 120 | Bb1 = 46 121 | B1 = 47 122 | 123 | C2 = 48 124 | Db2 = 49 125 | D2 = 50 126 | Eb2 = 51 127 | E2 = 52 128 | F2 = 53 129 | Gb2 = 54 130 | G2 = 55 131 | Ab2 = 56 132 | A2 = 57 133 | Bb2 = 58 134 | B2 = 59 135 | 136 | C = C3 = 60 137 | Db = Db3 = 61 138 | D = D3 = 62 139 | Eb = Eb3 = 63 140 | E = E3 = 64 141 | F = F3 = 65 142 | Gb = Gb3 = 66 143 | G = G3 = 67 144 | Ab = Ab3 = 68 145 | A = A3 = 69 146 | Bb = Bb3 = 70 147 | B = B3 = 71 148 | 149 | C4 = 72 150 | Db4 = 73 151 | D4 = 74 152 | Eb4 = 75 153 | E4 = 76 154 | F4 = 77 155 | Gb4 = 78 156 | G4 = 79 157 | Ab4 = 80 158 | A4 = 81 159 | Bb4 = 82 160 | B4 = 83 161 | 162 | C5 = 84 163 | Db5 = 85 164 | D5 = 86 165 | Eb5 = 87 166 | E5 = 88 167 | F5 = 89 168 | Gb5 = 90 169 | G5 = 91 170 | Ab5 = 92 171 | A5 = 93 172 | Bb5 = 94 173 | B5 = 95 174 | 175 | C6 = 96 176 | Db6 = 97 177 | D6 = 98 178 | Eb6 = 99 179 | E6 = 100 180 | F6 = 101 181 | Gb6 = 102 182 | G6 = 103 183 | Ab6 = 104 184 | A6 = 105 185 | Bb6 = 106 186 | B6 = 107 187 | 188 | C7 = 108 189 | Db7 = 109 190 | D7 = 110 191 | Eb7 = 111 192 | E7 = 112 193 | F7 = 113 194 | Gb7 = 114 195 | G7 = 115 196 | Ab7 = 116 197 | A7 = 117 198 | Bb7 = 118 199 | B7 = 119 200 | 201 | # western modes / chords 202 | 203 | ION = MAJ = Scale([0, 2, 4, 5, 7, 9, 11]) 204 | 205 | DOR = ION.rotate(1) 206 | 207 | PRG = SUSb9 = ION.rotate(2) 208 | 209 | LYD = ION.rotate(3) 210 | 211 | MYX = DOM = ION.rotate(4) 212 | 213 | AOL = NMI = ION.rotate(5) 214 | 215 | LOC = ION.rotate(6) 216 | 217 | MIN = HMI = Scale([0, 2, 3, 5, 7, 8, 11]) # Harmonic Minor 218 | 219 | MMI = Scale([0, 2, 3, 5, 7, 9, 11]) # Melodic Minor 220 | 221 | BLU = BMI = Scale([0, 3, 5, 6, 7, 10]) # Blues Minor 222 | 223 | BMA = Scale([0, 3, 4, 7, 9, 10]) # Blues major (From midipal/BitT source code) 224 | 225 | PEN = Scale([0, 2, 5, 7, 10]) 226 | 227 | PMA = Scale([0, 2, 4, 7, 9]) # Pentatonic major (From midipal/BitT source code) 228 | 229 | PMI = Scale([0, 3, 5, 7, 10]) # Pentatonic minor (From midipal/BitT source code) 230 | 231 | # world 232 | 233 | FLK = Scale([0, 1, 3, 4, 5, 7, 8, 10]) # Folk (From midipal/BitT source code) 234 | 235 | JPN = Scale([0, 1, 5, 7, 8]) # Japanese (From midipal/BitT source code) 236 | 237 | GYP = Scale([0, 2, 3, 6, 7, 8, 11]) # Gypsy (From MI Braids source code) 238 | 239 | ARB = Scale([0, 1, 4, 5, 7, 8, 11]) # Arabian (From MI Braids source code) 240 | 241 | FLM = Scale([0, 1, 4, 5, 7, 8, 10]) # Flamenco (From MI Braids source code) 242 | 243 | # other 244 | 245 | WHL = Scale([0, 2, 4, 6, 8, 10]) # Whole tone (From midipal/BitT source code) 246 | 247 | # chromatic 248 | 249 | CHR = Scale([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) 250 | 251 | # gamelan 252 | 253 | GML = Scale([0, 1, 3, 7, 8]) # Gamelan (From midipal/BitT source code) 254 | 255 | SDR = Scale([0, 2, 5, 7, 9]) 256 | 257 | PLG = Scale([0, 1, 3, 6, 7, 8, 10]) 258 | 259 | # personal 260 | 261 | JAM = Scale([0, 2, 3, 5, 6, 7, 10, 11]) 262 | 263 | # stepwise drums 264 | 265 | DRM = Scale([0, 2, 7, 14, 6, 10, 3, 39, 31, 13]) 266 | 267 | # 268 | 269 | R = 'R' # random 270 | Z = 'REST' # rest 271 | 272 | 273 | def g(note): 274 | # create grace note from named step 275 | return float(note) 276 | 277 | 278 | def v(note, v_scale=None): 279 | # create a note with scaled velocity from named (or unnamed) step 280 | # v_scale can be a single float value (the part before the decimal is ignored) 281 | # or it can be a tuple of (lo, hi) specifying a range for random scaling, e.g. v(C4, (.2, .9)) 282 | # else randomly generate v_scale between 0.17 and 0.999 283 | if type(v_scale) == float: 284 | v_scale = v_scale % 1 # ignore any part before the decimal 285 | elif type(v_scale) == tuple and len(v_scale): 286 | hi = 0.999 if len(v_scale) < 2 else v_scale[1] % 1 # allow specifying only lo, e.g. v(C, (.5,)) 287 | v_scale = uniform(v_scale[0] % 1, hi) 288 | else: 289 | v_scale = uniform(0.17, 0.999) 290 | return int(note) + v_scale 291 | 292 | 293 | def s(signal, a=1, r=1, p=0, b=0, v_scale=None): 294 | # Use signals to dynamically generate note pitches and velocities with base phase derived from the thread 295 | def f(t): 296 | pos = calc_pos(t._base_phase, r, p) 297 | n = signal(pos) 298 | if v_scale is not None: 299 | vs = v_scale(pos) if callable(v_scale) else v_scale 300 | n = v(n, v_scale=vs) 301 | return amp_bias(n, a, b, pos) 302 | 303 | return f 304 | -------------------------------------------------------------------------------- /braid/pattern.py: -------------------------------------------------------------------------------- 1 | import collections 2 | from random import choice, random 3 | from . import num_args 4 | from .signal import ease_in, ease_out 5 | from .logger import logger 6 | 7 | class Q(collections.deque): 8 | """Q is a wrapper around collections.deque for making rotating note 'queues' 9 | Set drunk=True to randomize the rotation direction, else always rotate right. 10 | e.g. Q([1, 2, 3]) returns 1 on the first cycle, then 2 on the next, then 3, then 1, etc... 11 | """ 12 | def __init__(self, iterable, drunk=False): 13 | self.drunk = drunk 14 | super(Q, self).__init__(iterable) 15 | 16 | class Pattern(list): 17 | 18 | """ Pattern is just a list (of whatever) that can be specified in compacted form 19 | ... with the addition of the Markov expansion of tuples and rotating Qs on calling resolve 20 | ... and some blending functions 21 | Set drunk = True to treat all Qs as if they are drunk = True, else defer to each Q's drunk property 22 | """ 23 | 24 | def __init__(self, value=[0], drunk=False): 25 | self.drunk = drunk 26 | list.__init__(self, value) 27 | 28 | def resolve(self): 29 | """Choose a path through the Markov chain""" 30 | return self._unroll(self._subresolve(self)) 31 | 32 | def _subresolve(self, pattern): 33 | """Resolve a subbranch of the pattern""" 34 | steps = [] 35 | for step in pattern: 36 | while type(step) == tuple or type(step) == Q: 37 | if type(step) == tuple: 38 | step = choice(step) 39 | else: 40 | coin = choice([0, 1]) 41 | if coin and (self.drunk or step.drunk): 42 | step.rotate(1) 43 | else: 44 | step.rotate(-1) 45 | step = step[-1] 46 | 47 | if type(step) == list: 48 | step = self._subresolve(step) 49 | steps.append(step) 50 | return steps 51 | 52 | def _unroll(self, pattern, divs=None, r=None): 53 | """Unroll a compacted form to a pattern with lcm steps""" 54 | if divs is None: 55 | divs = self._get_divs(pattern) 56 | r = [] 57 | elif r is None: 58 | r = [] 59 | for step in pattern: 60 | if type(step) == list: 61 | self._unroll(step, (divs // len(pattern)), r) 62 | else: 63 | r.append(step) 64 | for i in range((divs // len(pattern)) - 1): 65 | r.append(0) 66 | return r 67 | 68 | def _get_divs(self, pattern): 69 | """Find lcm for a subpattern""" 70 | subs = [(self._get_divs(step) if type(step) == list else 1) * len(pattern) for step in pattern] 71 | divs = subs[0] 72 | for step in subs[1:]: 73 | divs = lcm(divs, step) 74 | return divs 75 | 76 | def __repr__(self): 77 | return "P%s" % list.__repr__(self) 78 | 79 | def notes(self): 80 | """return a list of all values in pattern that are not 0 or REST""" 81 | return [n for n in self if n != 0 and n != 'REST'] 82 | 83 | def replace(self, value, target): 84 | list.__init__(self, [target if step == value else value for step in self]) 85 | 86 | def rotate(self, steps=1): 87 | # steps > 0 = right rotation, steps < 0 = left rotation 88 | if steps: 89 | steps = -(steps % len(self)) 90 | list.__init__(self, self[steps:] + self[:steps]) 91 | 92 | def blend(self, pattern_2, balance=0.5): 93 | l = blend(self, pattern_2, balance) 94 | list.__init__(self, l) 95 | 96 | def add(self, pattern_2): 97 | l = add(self, pattern_2) 98 | list.__init__(self, l) 99 | 100 | def xor(self, pattern_2): 101 | l = xor(self, pattern_2) 102 | list.__init__(self, l) 103 | 104 | def invert(self, off_note=0, note_list=None): 105 | """replace all occurrences of off_note with consecutive values from note_list (default = self.notes())""" 106 | """and replace all occurrences of NOT off_note with off_note""" 107 | """e.g. [1, 0, 2, 0, 3] becomes [0, 1, 0, 2, 0]""" 108 | if note_list is None: 109 | note_list = self.notes() 110 | inverted_pattern = [] 111 | i = 0 112 | for n in self: 113 | if n == off_note: 114 | inverted_pattern.append(note_list[i % len(note_list)]) 115 | i += 1 116 | else: 117 | inverted_pattern.append(off_note) 118 | list.__init__(self, inverted_pattern) 119 | 120 | 121 | def prep(pattern_1, pattern_2): 122 | if type(pattern_1) is not Pattern: 123 | pattern_1 = Pattern(pattern_1) 124 | if type(pattern_2) is not Pattern: 125 | pattern_2 = Pattern(pattern_2) 126 | p1_steps = pattern_1.resolve() 127 | p2_steps = pattern_2.resolve() 128 | pattern = [None] * lcm(len(p1_steps), len(p2_steps)) 129 | p1_div = len(pattern) / len(p1_steps) 130 | p2_div = len(pattern) / len(p2_steps) 131 | return pattern, p1_steps, p2_steps, p1_div, p2_div 132 | 133 | 134 | def blend(pattern_1, pattern_2, balance=0.5): 135 | """Probabalistically blend two Patterns""" 136 | pattern, p1_steps, p2_steps, p1_div, p2_div = prep(pattern_1, pattern_2) 137 | for i, cell in enumerate(pattern): 138 | if i % p1_div == 0 and i % p2_div == 0: 139 | if random() > balance: 140 | pattern[i] = p1_steps[int(i / p1_div)] 141 | else: 142 | pattern[i] = p2_steps[int(i / p2_div)] 143 | elif i % p1_div == 0: 144 | if random() > ease_out()(balance): # avoid empty middle from linear blend 145 | pattern[i] = p1_steps[int(i / p1_div)] 146 | elif i % p2_div == 0: 147 | if random() <= ease_in()(balance): 148 | pattern[i] = p2_steps[int(i / p2_div)] 149 | pattern = Pattern(pattern) 150 | return pattern 151 | 152 | 153 | def add(pattern_1, pattern_2): 154 | """Produce the AND of two patterns""" 155 | pattern, p1_steps, p2_steps, p1_div, p2_div = prep(pattern_1, pattern_2) 156 | for i, cell in enumerate(pattern): 157 | step_1 = p1_steps[int(i / p1_div)] 158 | step_2 = p2_steps[int(i / p2_div)] 159 | if i % p1_div == 0 and step_1 != 0 and step_1 != None: 160 | pattern[i] = step_1 161 | elif i % p2_div == 0 and step_2 != 0 and step_2 != None: 162 | pattern[i] = p2_steps[int(i / p2_div)] 163 | pattern = Pattern(pattern) 164 | return pattern 165 | 166 | 167 | def xor(pattern_1, pattern_2): 168 | """Produce the XOR of two patterns""" 169 | pattern, p1_steps, p2_steps, p1_div, p2_div = prep(pattern_1, pattern_2) 170 | for i, cell in enumerate(pattern): 171 | step_1 = p1_steps[int(i / p1_div)] 172 | step_2 = p2_steps[int(i / p2_div)] 173 | if i % p1_div == 0 and step_1 != 0 and step_1 != None and i % p2_div == 0 and step_2 != 0 and step_2 != None: 174 | pass 175 | elif i % p1_div == 0 and step_1 != 0 and step_1 != None: 176 | pattern[i] = p1_steps[int(i / p1_div)] 177 | elif i % p2_div == 0 and step_2 != 0 and step_2 != None: 178 | pattern[i] = p2_steps[int(i / p2_div)] 179 | pattern = Pattern(pattern) 180 | return pattern 181 | 182 | 183 | def lcm(a, b): 184 | gcd, tmp = a, b 185 | while tmp != 0: 186 | gcd, tmp = tmp, gcd % tmp 187 | return a * b // gcd 188 | 189 | 190 | def euc(steps, pulses, rotation=0, invert=False, note=1, off_note=0, note_list=None, off_note_list=None): 191 | steps = int(steps) 192 | pulses = int(pulses) 193 | if pulses > steps: 194 | logger.info("Make pulses > steps") 195 | return None 196 | pattern = [] 197 | counts = [] 198 | remainders = [] 199 | divisor = steps - pulses 200 | remainders.append(pulses) 201 | level = 0 202 | while True: 203 | counts.append(divisor // remainders[level]) 204 | remainders.append(divisor % remainders[level]) 205 | divisor = remainders[level] 206 | level = level + 1 207 | if remainders[level] <= 1: 208 | break 209 | counts.append(divisor) 210 | 211 | def build(level): 212 | if level == -1: 213 | pattern.append(off_note) 214 | elif level == -2: 215 | pattern.append(note) 216 | else: 217 | for i in range(0, counts[level]): 218 | build(level - 1) 219 | if remainders[level] != 0: 220 | build(level - 2) 221 | 222 | build(level) 223 | i = pattern.index(note) 224 | pattern = pattern[i:] + pattern[0:i] 225 | 226 | if rotation: 227 | pattern = Pattern(pattern) 228 | pattern.rotate(rotation) 229 | pattern = list(pattern) 230 | if note_list is None: 231 | note_list = [note] 232 | if off_note_list is None: 233 | off_note_list = [off_note] 234 | pulse = off_note if invert else note 235 | final_pattern = [] 236 | i = j = 0 237 | for n in pattern: 238 | if n == pulse: 239 | final_pattern.append(note_list[i % len(note_list)]) 240 | i += 1 241 | else: 242 | final_pattern.append(off_note_list[j % len(off_note_list)]) 243 | j += 1 244 | 245 | return final_pattern 246 | 247 | -------------------------------------------------------------------------------- /braid/tween.py: -------------------------------------------------------------------------------- 1 | import collections, math 2 | from random import random, uniform, choice 3 | from .signal import linear, sine, pulse, inverse_linear, triangle 4 | from .pattern import Q, Pattern, blend, euc, add, xor 5 | from .core import driver 6 | from .logger import logger 7 | 8 | 9 | class Tween(object): 10 | 11 | def __init__(self, target_value, cycles, signal_f=linear(), on_end=None, osc=False, phase_offset=0, random=False, saw=False, start_value=None): 12 | self.target_value = target_value 13 | self.cycles = cycles 14 | self.signal_f = signal_f 15 | self.end_f = on_end 16 | self.osc = osc 17 | self.saw = saw 18 | self.phase_offset = phase_offset 19 | self.start_value = start_value 20 | if start_value is not None: 21 | self._min_value = min(self.start_value, self.target_value) 22 | self._max_value = max(self.start_value, self.target_value) 23 | self.random = random 24 | self.rand_lock = False 25 | self._random_value = 0 26 | self._lock_values = collections.deque([0]) 27 | self._lag = 1. 28 | self._step_len = 1/4 29 | self._steps = [0., .25, .5, .75] 30 | self._step = 0 31 | self.finished = False 32 | 33 | 34 | def start(self, thread, start_value): 35 | self.thread = thread 36 | self._step = 0 37 | if self.start_value is None: 38 | self.start_value = start_value 39 | self._min_value = min(self.start_value, self.target_value) 40 | self._max_value = max(self.start_value, self.target_value) 41 | self.start_cycle = float(math.ceil(self.thread._cycles)) # tweens always start on next cycle 42 | 43 | @property 44 | def value(self): 45 | if self.finished: 46 | return self.target_value 47 | if self.random: 48 | if self._steps[self._step] <= self.position < self._steps[self._step] + self._step_len: 49 | if self.rand_lock: 50 | self._lock_values.rotate(-1) 51 | self._random_value = self._lock_values[-1] 52 | else: 53 | lag_diff = (uniform(self._min_value, self._max_value) - self._random_value) * self._lag 54 | self._random_value += lag_diff 55 | self._step = (self._step + 1) % len(self._steps) 56 | return self._random_value 57 | else: 58 | return self.calc_value(self.signal_position) 59 | 60 | @property 61 | def signal_position(self): # can reference this to see where we are on the signal function 62 | return self.signal_f((self.position + self.phase_offset) % 1.0) 63 | 64 | @property 65 | def position(self): # can reference this to see where we are in the tween 66 | if self.cycles == 0.0: 67 | return 1.0 68 | position = (self.thread._cycles - self.start_cycle) / self.cycles 69 | if position <= 0.0: 70 | position = 0.0 71 | if position >= 1.0: 72 | position = 1.0 73 | if self.end_f is not None: 74 | try: 75 | self.end_f() 76 | except Exception as e: 77 | logger.error("[Error tween.on_end: %s]" % e) 78 | if self.osc or self.saw: 79 | if self.osc: 80 | sv = self.target_value 81 | self.target_value = self.start_value 82 | self.start_value = sv 83 | self.start_cycle = self.thread._cycles - ((self.thread._cycles - self.start_cycle) - self.cycles) 84 | position = abs(1 - position) 85 | else: 86 | self.finished = True 87 | logger.info('finished is true') 88 | return position 89 | 90 | @property 91 | def step_len(self): 92 | return self._step_len 93 | 94 | @step_len.setter 95 | def step_len(self, length): 96 | steps = [] 97 | i = 0 98 | while 0 <= i < 1.0: 99 | steps.append(i) 100 | i += length 101 | self._steps = steps 102 | self._step_len = length 103 | 104 | 105 | 106 | class ScalarTween(Tween): 107 | 108 | def calc_value(self, position): 109 | value = (position * (self.target_value - self.start_value)) + self.start_value 110 | return value 111 | 112 | 113 | class ChordTween(Tween): 114 | 115 | def calc_value(self, position): 116 | if random() > position: 117 | return self.start_value 118 | else: 119 | return self.target_value 120 | 121 | 122 | class PatternTween(Tween): 123 | 124 | def calc_value(self, position): 125 | return blend(self.start_value, self.target_value, position) 126 | 127 | 128 | class RateTween(ScalarTween): 129 | 130 | def start(self, thread, start_value): 131 | self.thread = driver # rate tweens are based on the driver reference 132 | self.syncer = thread # this is the actual reference to the current thread 133 | self.start_value = start_value 134 | self.start_cycle = driver._cycles # float(math.ceil(driver._cycles)) # it's a float, so if you ceil this, it's always the _next_ edge, even if it should be "0" 135 | 136 | def get_phase(self): 137 | driver_cycles_remaining = self.cycles - (driver._cycles - self.start_cycle) 138 | if driver_cycles_remaining <= 0: 139 | return None 140 | time_remaining = driver_cycles_remaining / driver.rate 141 | acceleration = ((self.target_value * driver.rate) - (self.syncer.rate * driver.rate)) / time_remaining 142 | syncer_cycles_remaining = (self.syncer.rate * driver.rate * time_remaining) + (0.5 * (acceleration * (time_remaining * time_remaining))) 143 | cycles_at_completion = syncer_cycles_remaining + self.syncer._cycles 144 | phase_at_completion = cycles_at_completion % 1.0 145 | phase_correction = phase_at_completion 146 | phase_correction *= -1 147 | if phase_correction < 0.0: 148 | phase_correction = 1.0 + phase_correction 149 | return phase_correction 150 | 151 | 152 | def tween( 153 | value, 154 | cycles, 155 | signal_f=linear(), 156 | on_end=None, 157 | osc=False, 158 | phase_offset=0, 159 | random=False, 160 | saw=False, 161 | start=None, 162 | ): 163 | if type(value) == int or type(value) == float: 164 | return ScalarTween(value, cycles, signal_f, on_end, osc, phase_offset, random, saw, start) 165 | if type(value) == tuple: 166 | return ChordTween(value, cycles, signal_f, on_end, osc, phase_offset, False, saw, start) 167 | if type(value) == list: # careful, lists are always patterns 168 | value = Pattern(value) 169 | if type(value) == Pattern: 170 | return PatternTween(value, cycles, signal_f, on_end, osc, phase_offset, False, saw, start) 171 | 172 | def osc(start, value, cycles, signal_f=linear(), phase_offset=0, on_end=None): 173 | return tween( 174 | value, 175 | cycles, 176 | signal_f=signal_f, 177 | on_end=on_end, 178 | osc=True, 179 | phase_offset=phase_offset, 180 | start=start, 181 | ) 182 | 183 | def saw(start, value, cycles, up=True, signal_f=linear(), phase_offset=0, on_end=None): 184 | if not up and signal_f == linear(): 185 | signal_f = inverse_linear() 186 | return tween( 187 | value, 188 | cycles, 189 | signal_f=signal_f, 190 | on_end=on_end, 191 | phase_offset=phase_offset, 192 | saw=True, 193 | start=start, 194 | ) 195 | 196 | def sin(start, value, cycles, phase_offset=0, loop=True, on_end=None): 197 | return tween( 198 | value, 199 | cycles, 200 | signal_f=sine(), 201 | on_end=on_end, 202 | phase_offset=phase_offset, 203 | saw=loop, 204 | start=start, 205 | ) 206 | 207 | def tri(start, value, cycles, symmetry=0.5, phase_offset=0, loop=True, on_end=None): 208 | return tween( 209 | value, 210 | cycles, 211 | signal_f=triangle(symmetry), 212 | on_end=on_end, 213 | phase_offset=phase_offset, 214 | saw=loop, 215 | start=start, 216 | ) 217 | 218 | def pw(start, value, cycles, width=0.5, phase_offset=0, loop=True, on_end=None): 219 | return tween( 220 | value, 221 | cycles, 222 | signal_f=pulse(width), 223 | on_end=on_end, 224 | phase_offset=phase_offset, 225 | saw=loop, 226 | start=start, 227 | ) 228 | 229 | def sh(lo, hi, cycles, step_len, lag=1., loop=True, lock=False, lock_len=None, on_end=None): 230 | t = tween( 231 | hi, 232 | cycles, 233 | start=lo, 234 | on_end=on_end, 235 | random=True, 236 | saw=loop, 237 | ) 238 | t.step_len = step_len 239 | t._lag = lag # scale the distance between the random values 240 | if lock: # pre-generate a list of random values to choose from instead of generating new ones continuously 241 | lock_len = lock_len if lock_len else len(t._steps) 242 | t.rand_lock = True 243 | lock_vals = collections.deque([lo + (uniform(t._min_value, t._max_value) - lo) * lag]) 244 | for x in range(1, lock_len): 245 | lock_vals.append(lock_vals[x - 1] + (uniform(t._min_value, t._max_value) - lock_vals[x - 1]) * lag) 246 | t._lock_values = lock_vals 247 | return t 248 | -------------------------------------------------------------------------------- /braid/thread.py: -------------------------------------------------------------------------------- 1 | import collections, yaml, os, math 2 | from .core import driver, LIVECODING 3 | from . import num_args, midi_out 4 | from .signal import linear 5 | from .notation import * 6 | from .tween import * 7 | from .logger import logger 8 | 9 | 10 | class Thread(object): 11 | """Class definitions""" 12 | 13 | threads = driver.threads 14 | 15 | @classmethod 16 | def add_attr(cls, name, default=0): 17 | """Add a property with tweening capability (won't send MIDI)""" 18 | 19 | def getter(self): 20 | if isinstance(getattr(self, "_%s" % name), Tween): 21 | return getattr(self, "_%s" % name).value 22 | return getattr(self, "_%s" % name) 23 | 24 | def setter(self, value): 25 | if isinstance(value, Tween): 26 | value.start(self, getattr(self, name)) 27 | if value is True: 28 | value = 127 29 | if value is False: 30 | value = 0 31 | setattr(self, "_%s" % name, value) 32 | 33 | setattr(cls, "_%s" % name, default) 34 | setattr(cls, name, property(getter, setter)) 35 | 36 | @classmethod 37 | def setup(cls): 38 | # standard properties 39 | Thread.add_attr('transpose', 0) 40 | Thread.add_attr('transpose_step_len', 1) 41 | Thread.add_attr('chord', None) 42 | Thread.add_attr('velocity', 1.0) 43 | Thread.add_attr('grace', 0.75) 44 | Thread.add_attr('phase', 0.0) 45 | Thread.add_attr('micro', None) 46 | Thread.add_attr('controls', None) 47 | 48 | """Instance definitions""" 49 | 50 | def __setattr__(self, key, value): 51 | if not key == "_attr_frozen" and self._attr_frozen and not hasattr(self, key): 52 | logger.info("[No property %s]" % key) 53 | return 54 | try: 55 | object.__setattr__(self, key, value) 56 | except Exception as e: 57 | logger.error("[Error: \"%s\"]" % e) 58 | 59 | def __getattr__(self, key): 60 | logger.info("[No property %s]" % key) 61 | return None 62 | 63 | def add(self, param, default=0): 64 | self._attr_frozen = False 65 | self.__class__.add_attr(param, default) 66 | self._attr_frozen = True 67 | 68 | def __init__(self, channel, sync=True): 69 | Thread.threads.append(self) 70 | 71 | # private reference variables 72 | self._attr_frozen = False 73 | self._channel = channel 74 | self._running = False 75 | self._cycles = 0.0 76 | self._base_phase = 0.0 77 | self._last_edge = 0 78 | self._index = -1 79 | self._transpose_index = -1 80 | self._steps = [0] 81 | self._previous_pitch = 60 82 | self._previous_step = 1 83 | self.__phase_correction = 0.0 84 | self._control_values = {} 85 | self._triggers = [] 86 | self._sync = sync 87 | self._start_lock = False 88 | 89 | # specialized properties 90 | self.pattern = [0] 91 | self.rate = 1.0 92 | self.keyboard = False 93 | self.micro = linear() 94 | 95 | logger.info("[Created thread on channel %d]" % self._channel) 96 | self._attr_frozen = True 97 | 98 | if not LIVECODING: 99 | self.start() 100 | 101 | def update(self, delta_t): 102 | """Run each tick and update the state of the Thread""" 103 | if not self._running: 104 | return 105 | self.update_controls() 106 | self._cycles += delta_t * self.rate * driver.rate 107 | if self._sync and isinstance(self._rate, Tween): 108 | pc = self._rate.get_phase() 109 | if pc is not None: 110 | self.__phase_correction.target_value = pc 111 | self._base_phase = (self._cycles + self.phase + self._phase_correction) % 1.0 112 | if self.micro is not None: 113 | self._base_phase = self.micro(self._base_phase) 114 | i = int(self._base_phase * len(self._steps)) 115 | if i != self._index or ( 116 | len(self._steps) == 1 and int(self._cycles) != self._last_edge): # contingency for whole notes 117 | if self._start_lock: 118 | self._index = self._transpose_index = i 119 | else: 120 | self._index = (self._index + 1) % len(self._steps) # dont skip steps 121 | if type(self.transpose) == list and not self._index % int(self.transpose_step_len): 122 | self._transpose_index = (self._transpose_index + 1) % len(self.transpose) 123 | if self._index == 0: 124 | self.update_triggers() 125 | if isinstance(self.pattern, Tween): # pattern tweens only happen on an edge 126 | pattern = self.pattern.value() 127 | else: 128 | pattern = self.pattern 129 | self._steps = pattern.resolve() # new patterns kick in here 130 | if self._start_lock: 131 | self._start_lock = False 132 | else: 133 | step = self._steps[self._index] 134 | self.play(step) 135 | self._last_edge = int(self._cycles) 136 | 137 | def update_controls(self): 138 | """Check if MIDI attributes have changed, and if so send""" 139 | if not hasattr(self, "controls") or self.controls is None: 140 | return 141 | for control in self.controls: 142 | value = int(getattr(self, control)) 143 | if self._channel not in self._control_values: 144 | self._control_values[self._channel] = {} 145 | if control not in self._control_values[self._channel] or value != self._control_values[self._channel][ 146 | control]: 147 | midi_out.send_control(self._channel, midi_clamp(self.controls[control]), value) 148 | self._control_values[self._channel][control] = value 149 | # logger.info("[CTRL %d: %s %s]" % (self._channel, control, value)) 150 | 151 | def update_triggers(self): 152 | """Check trigger functions a fire as necessary""" 153 | updated = False 154 | for t, trigger in enumerate(self._triggers): 155 | trigger[3] += 1 # increment edge 156 | if (trigger[1] + 1) - trigger[ 157 | 3] == 0: # have to add 1 because trigger[1] is total 'elapsed' cycles but we're counting edges 158 | try: 159 | if num_args(trigger[0]): 160 | trigger[0](self) 161 | else: 162 | trigger[0]() 163 | except Exception as e: 164 | logger.error("\n[Trigger error: %s]" % e) 165 | if trigger[2] is True: 166 | self.trigger(trigger[0], trigger[1], True) # create new trigger with same properties 167 | else: 168 | trigger[2] -= 1 169 | if trigger[2] > 0: 170 | self.trigger(trigger[0], trigger[1], trigger[2] - 1) # same, but decrement repeats 171 | self._triggers[t] = None # clear this trigger 172 | updated = True 173 | if updated: 174 | self._triggers = [trigger for trigger in self._triggers if trigger is not None] 175 | 176 | def play(self, step, velocity=None): 177 | """Interpret a step value to play a note""" 178 | while isinstance(step, collections.abc.Callable): 179 | step = step(self) if num_args(step) else step() 180 | self.update_controls() # to handle note-level CC changes 181 | if type(step) == float: # use the part after the decimal to scale velocity 182 | v = step % 1 183 | v = self.grace if v == 0.0 else v # if decimal part is 0.0 fallback to self.grace to scale velocity 184 | else: 185 | v = 1.0 186 | step = int(step) if type(step) == float else step 187 | if step == Z: 188 | self.rest() 189 | elif step == 0 or step is None: 190 | self.hold() 191 | else: 192 | transposition = self.transpose 193 | if type(transposition) == list: 194 | transposition = transposition[self._transpose_index % len(transposition)] 195 | while type(transposition) == tuple: 196 | transposition = choice(transposition) 197 | if self.chord is None: 198 | pitch = step + int(transposition) 199 | else: 200 | root, scale = self.chord 201 | try: 202 | pitch = scale.quantize(root + int(transposition) + scale[step]) 203 | except ScaleError as e: 204 | logger.error("\n[Error: %s]" % e) 205 | return 206 | velocity = 1.0 - (random() * 0.05) if velocity is None else velocity 207 | velocity *= self.velocity 208 | velocity *= v 209 | self.note(pitch, velocity) 210 | if step != 0: 211 | self._previous_step = step 212 | 213 | def note(self, pitch, velocity): 214 | """Override for custom MIDI behavior""" 215 | if self.keyboard is True and velocity == 0: 216 | midi_out.send_note(self._channel, pitch, 0) 217 | else: 218 | if self.keyboard is not True: 219 | midi_out.send_note(self._channel, self._previous_pitch, 0) 220 | midi_out.send_note(self._channel, pitch, midi_clamp(velocity * 127)) 221 | self._previous_pitch = pitch 222 | 223 | def hold(self): 224 | """Override to add behavior to held notes, otherwise nothing""" 225 | pass 226 | 227 | def rest(self): 228 | """Send a MIDI off""" 229 | midi_out.send_note(self._channel, self._previous_pitch, 0) 230 | 231 | def end(self): 232 | """Override to add behavior for the end of the piece, otherwise rest""" 233 | self.rest() 234 | 235 | """Specialized parameters""" 236 | 237 | # Convenience methods for getting/setting chord root 238 | # Does NOT support tweening, for that use chord or transpose 239 | @property 240 | def root(self): 241 | if isinstance(self.chord, Tween): 242 | return self.chord.value[0] 243 | return self.chord[0] if self.chord else None 244 | 245 | @root.setter 246 | def root(self, root): 247 | if isinstance(self.chord, Tween): 248 | scale = self.chord.value[1] 249 | else: 250 | scale = self.chord[1] if self.chord else CHR # Default to Chromatic Scale 251 | self.chord = root, scale 252 | 253 | # Convenience methods for getting/setting chord scale 254 | # Does NOT support tweening, for that use chord 255 | @property 256 | def scale(self): 257 | if isinstance(self.chord, Tween): 258 | return self.chord.value[1] 259 | return self.chord[1] if self.chord else None 260 | 261 | @scale.setter 262 | def scale(self, scale): 263 | if isinstance(self.chord, Tween): 264 | root = self.chord.value[0] 265 | else: 266 | root = self.chord[0] if self.chord else C # Default to Middle C 267 | self.chord = root, scale 268 | 269 | @property 270 | def channel(self): 271 | return self._channel 272 | 273 | @channel.setter 274 | def channel(self, channel): 275 | self._channel = channel 276 | 277 | @property 278 | def pattern(self): 279 | if isinstance(self._pattern, Tween): 280 | return self._pattern.value 281 | return self._pattern 282 | 283 | @pattern.setter 284 | def pattern(self, pattern): 285 | if isinstance(pattern, Tween): 286 | pattern.start(self, self.pattern) 287 | else: 288 | pattern = Pattern(pattern) 289 | self._pattern = pattern 290 | 291 | @property 292 | def rate(self): 293 | if isinstance(self._rate, Tween): 294 | return self._rate.value 295 | return self._rate 296 | 297 | @rate.setter 298 | def rate(self, rate): 299 | if isinstance(rate, Tween): 300 | rate = RateTween(rate.target_value, rate.cycles, rate.signal_f, rate.end_f, rate.osc) # downcast tween 301 | if self._sync: 302 | def rt(): 303 | rate.start(self, self.rate) 304 | phase_correction = tween(89.9, rate.cycles) # make a tween for the subsequent phase correction 305 | phase_correction.start(driver, self._phase_correction) 306 | self.__phase_correction = phase_correction 307 | self._rate = rate 308 | 309 | self.trigger( 310 | rt) # this wont work unless it happens on an edge, and we need to do that here unlike other tweens 311 | return 312 | else: 313 | rate.start(self, self.rate) 314 | self._rate = rate 315 | 316 | @property 317 | def _phase_correction(self): 318 | if isinstance(self.__phase_correction, Tween): 319 | return self.__phase_correction.value 320 | return self.__phase_correction 321 | 322 | """Sequencing""" 323 | 324 | def start(self, thread=None): 325 | self._running = True 326 | if thread is not None: 327 | self._cycles = math.floor(thread._cycles) 328 | time_to_edge = (thread._cycles % 1.0) / thread.rate 329 | self._cycles += time_to_edge * self.rate 330 | 331 | self._last_edge = 0 332 | self._index = -1 333 | self._start_lock = True 334 | else: 335 | self._cycles = 0.0 336 | self._last_edge = 0 337 | self._index = -1 338 | logger.info("[Thread started on channel %s]" % self._channel) 339 | 340 | def stop(self): 341 | self._running = False 342 | self.end() 343 | logger.info("[Thread stopped on channel %s]" % self._channel) 344 | 345 | def trigger(self, f=None, cycles=0, repeat=0): 346 | if f is None and repeat is False: 347 | self._triggers = [trigger for trigger in self._triggers if trigger[2] is not True] # filter repeat=True 348 | elif f is False: 349 | self._triggers = [] 350 | else: 351 | try: 352 | assert (callable(f)) 353 | if cycles == 0: 354 | assert repeat == 0 355 | except AssertionError as e: 356 | logger.error("\n[Bad arguments for trigger]") 357 | else: 358 | self._triggers.append([f, cycles, repeat, 0]) # last parameter is cycle edges so far 359 | 360 | 361 | def midi_clamp(value): 362 | """Clamp value to int between 0-127""" 363 | if value < 0: 364 | value = 0 365 | if value > 127: 366 | value = 127 367 | return int(value) 368 | 369 | 370 | def make(controls={}, defaults={}): 371 | """Make a Thread with MIDI control values and defaults (will send MIDI)""" 372 | name = "T%s" % str(random())[-4:] # name doesn't really do anything 373 | T = type(name, (Thread,), {}) 374 | T.add_attr('controls', controls) 375 | for control in controls: 376 | T.add_attr(control, defaults[control] if control in defaults else 0) # mid-level for knobs, off for switches 377 | return T 378 | 379 | 380 | Thread.setup() 381 | 382 | synths = {} 383 | try: 384 | with open(os.path.join(os.path.dirname(__file__), "synths.yaml")) as f: 385 | synths.update(yaml.safe_load(f)) 386 | except FileNotFoundError as e: 387 | pass 388 | if len(synths): 389 | for synth, params in synths.items(): 390 | try: 391 | controls = params['controls'] 392 | defaults = params['defaults'] 393 | exec("%s = make(controls, defaults)" % synth) 394 | except Exception as e: 395 | logger.warning("Warning: failed to load %s:" % synth, e) 396 | logger.info("Loaded synths") 397 | -------------------------------------------------------------------------------- /docs/github-markdown.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: octicons-link; 3 | src: url(data:font/woff;charset=utf-8;base64,d09GRgABAAAAAAZwABAAAAAACFQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEU0lHAAAGaAAAAAgAAAAIAAAAAUdTVUIAAAZcAAAACgAAAAoAAQAAT1MvMgAAAyQAAABJAAAAYFYEU3RjbWFwAAADcAAAAEUAAACAAJThvmN2dCAAAATkAAAABAAAAAQAAAAAZnBnbQAAA7gAAACyAAABCUM+8IhnYXNwAAAGTAAAABAAAAAQABoAI2dseWYAAAFsAAABPAAAAZwcEq9taGVhZAAAAsgAAAA0AAAANgh4a91oaGVhAAADCAAAABoAAAAkCA8DRGhtdHgAAAL8AAAADAAAAAwGAACfbG9jYQAAAsAAAAAIAAAACABiATBtYXhwAAACqAAAABgAAAAgAA8ASm5hbWUAAAToAAABQgAAAlXu73sOcG9zdAAABiwAAAAeAAAAME3QpOBwcmVwAAAEbAAAAHYAAAB/aFGpk3jaTY6xa8JAGMW/O62BDi0tJLYQincXEypYIiGJjSgHniQ6umTsUEyLm5BV6NDBP8Tpts6F0v+k/0an2i+itHDw3v2+9+DBKTzsJNnWJNTgHEy4BgG3EMI9DCEDOGEXzDADU5hBKMIgNPZqoD3SilVaXZCER3/I7AtxEJLtzzuZfI+VVkprxTlXShWKb3TBecG11rwoNlmmn1P2WYcJczl32etSpKnziC7lQyWe1smVPy/Lt7Kc+0vWY/gAgIIEqAN9we0pwKXreiMasxvabDQMM4riO+qxM2ogwDGOZTXxwxDiycQIcoYFBLj5K3EIaSctAq2kTYiw+ymhce7vwM9jSqO8JyVd5RH9gyTt2+J/yUmYlIR0s04n6+7Vm1ozezUeLEaUjhaDSuXHwVRgvLJn1tQ7xiuVv/ocTRF42mNgZGBgYGbwZOBiAAFGJBIMAAizAFoAAABiAGIAznjaY2BkYGAA4in8zwXi+W2+MjCzMIDApSwvXzC97Z4Ig8N/BxYGZgcgl52BCSQKAA3jCV8CAABfAAAAAAQAAEB42mNgZGBg4f3vACQZQABIMjKgAmYAKEgBXgAAeNpjYGY6wTiBgZWBg2kmUxoDA4MPhGZMYzBi1AHygVLYQUCaawqDA4PChxhmh/8ODDEsvAwHgMKMIDnGL0x7gJQCAwMAJd4MFwAAAHjaY2BgYGaA4DAGRgYQkAHyGMF8NgYrIM3JIAGVYYDT+AEjAwuDFpBmA9KMDEwMCh9i/v8H8sH0/4dQc1iAmAkALaUKLgAAAHjaTY9LDsIgEIbtgqHUPpDi3gPoBVyRTmTddOmqTXThEXqrob2gQ1FjwpDvfwCBdmdXC5AVKFu3e5MfNFJ29KTQT48Ob9/lqYwOGZxeUelN2U2R6+cArgtCJpauW7UQBqnFkUsjAY/kOU1cP+DAgvxwn1chZDwUbd6CFimGXwzwF6tPbFIcjEl+vvmM/byA48e6tWrKArm4ZJlCbdsrxksL1AwWn/yBSJKpYbq8AXaaTb8AAHja28jAwOC00ZrBeQNDQOWO//sdBBgYGRiYWYAEELEwMTE4uzo5Zzo5b2BxdnFOcALxNjA6b2ByTswC8jYwg0VlNuoCTWAMqNzMzsoK1rEhNqByEyerg5PMJlYuVueETKcd/89uBpnpvIEVomeHLoMsAAe1Id4AAAAAAAB42oWQT07CQBTGv0JBhagk7HQzKxca2sJCE1hDt4QF+9JOS0nbaaYDCQfwCJ7Au3AHj+LO13FMmm6cl7785vven0kBjHCBhfpYuNa5Ph1c0e2Xu3jEvWG7UdPDLZ4N92nOm+EBXuAbHmIMSRMs+4aUEd4Nd3CHD8NdvOLTsA2GL8M9PODbcL+hD7C1xoaHeLJSEao0FEW14ckxC+TU8TxvsY6X0eLPmRhry2WVioLpkrbp84LLQPGI7c6sOiUzpWIWS5GzlSgUzzLBSikOPFTOXqly7rqx0Z1Q5BAIoZBSFihQYQOOBEdkCOgXTOHA07HAGjGWiIjaPZNW13/+lm6S9FT7rLHFJ6fQbkATOG1j2OFMucKJJsxIVfQORl+9Jyda6Sl1dUYhSCm1dyClfoeDve4qMYdLEbfqHf3O/AdDumsjAAB42mNgYoAAZQYjBmyAGYQZmdhL8zLdDEydARfoAqIAAAABAAMABwAKABMAB///AA8AAQAAAAAAAAAAAAAAAAABAAAAAA==) format('woff'); 4 | } 5 | 6 | .markdown-body { 7 | -ms-text-size-adjust: 100%; 8 | -webkit-text-size-adjust: 100%; 9 | line-height: 1.5; 10 | color: #333; 11 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol"; 12 | font-size: 16px; 13 | line-height: 1.5; 14 | word-wrap: break-word; 15 | } 16 | 17 | .markdown-body .pl-c { 18 | color: #969896; 19 | } 20 | 21 | .markdown-body .pl-c1, 22 | .markdown-body .pl-s .pl-v { 23 | color: #0086b3; 24 | } 25 | 26 | .markdown-body .pl-e, 27 | .markdown-body .pl-en { 28 | color: #795da3; 29 | } 30 | 31 | .markdown-body .pl-smi, 32 | .markdown-body .pl-s .pl-s1 { 33 | color: #333; 34 | } 35 | 36 | .markdown-body .pl-ent { 37 | color: #63a35c; 38 | } 39 | 40 | .markdown-body .pl-k { 41 | color: #a71d5d; 42 | } 43 | 44 | .markdown-body .pl-s, 45 | .markdown-body .pl-pds, 46 | .markdown-body .pl-s .pl-pse .pl-s1, 47 | .markdown-body .pl-sr, 48 | .markdown-body .pl-sr .pl-cce, 49 | .markdown-body .pl-sr .pl-sre, 50 | .markdown-body .pl-sr .pl-sra { 51 | color: #183691; 52 | } 53 | 54 | .markdown-body .pl-v { 55 | color: #ed6a43; 56 | } 57 | 58 | .markdown-body .pl-id { 59 | color: #b52a1d; 60 | } 61 | 62 | .markdown-body .pl-ii { 63 | color: #f8f8f8; 64 | background-color: #b52a1d; 65 | } 66 | 67 | .markdown-body .pl-sr .pl-cce { 68 | font-weight: bold; 69 | color: #63a35c; 70 | } 71 | 72 | .markdown-body .pl-ml { 73 | color: #693a17; 74 | } 75 | 76 | .markdown-body .pl-mh, 77 | .markdown-body .pl-mh .pl-en, 78 | .markdown-body .pl-ms { 79 | font-weight: bold; 80 | color: #1d3e81; 81 | } 82 | 83 | .markdown-body .pl-mq { 84 | color: #008080; 85 | } 86 | 87 | .markdown-body .pl-mi { 88 | font-style: italic; 89 | color: #333; 90 | } 91 | 92 | .markdown-body .pl-mb { 93 | font-weight: bold; 94 | color: #333; 95 | } 96 | 97 | .markdown-body .pl-md { 98 | color: #bd2c00; 99 | background-color: #ffecec; 100 | } 101 | 102 | .markdown-body .pl-mi1 { 103 | color: #55a532; 104 | background-color: #eaffea; 105 | } 106 | 107 | .markdown-body .pl-mdr { 108 | font-weight: bold; 109 | color: #795da3; 110 | } 111 | 112 | .markdown-body .pl-mo { 113 | color: #1d3e81; 114 | } 115 | 116 | .markdown-body .octicon { 117 | display: inline-block; 118 | vertical-align: text-top; 119 | fill: currentColor; 120 | } 121 | 122 | .markdown-body a { 123 | background-color: transparent; 124 | -webkit-text-decoration-skip: objects; 125 | } 126 | 127 | .markdown-body a:active, 128 | .markdown-body a:hover { 129 | outline-width: 0; 130 | } 131 | 132 | .markdown-body strong { 133 | font-weight: inherit; 134 | } 135 | 136 | .markdown-body strong { 137 | font-weight: bolder; 138 | } 139 | 140 | .markdown-body h1 { 141 | font-size: 2em; 142 | margin: 0.67em 0; 143 | } 144 | 145 | .markdown-body img { 146 | border-style: none; 147 | } 148 | 149 | .markdown-body svg:not(:root) { 150 | overflow: hidden; 151 | } 152 | 153 | .markdown-body code, 154 | .markdown-body kbd, 155 | .markdown-body pre { 156 | font-family: monospace, monospace; 157 | font-size: 1em; 158 | } 159 | 160 | .markdown-body hr { 161 | box-sizing: content-box; 162 | height: 0; 163 | overflow: visible; 164 | } 165 | 166 | .markdown-body input { 167 | font: inherit; 168 | margin: 0; 169 | } 170 | 171 | .markdown-body input { 172 | overflow: visible; 173 | } 174 | 175 | .markdown-body [type="checkbox"] { 176 | box-sizing: border-box; 177 | padding: 0; 178 | } 179 | 180 | .markdown-body * { 181 | box-sizing: border-box; 182 | } 183 | 184 | .markdown-body input { 185 | font-family: inherit; 186 | font-size: inherit; 187 | line-height: inherit; 188 | } 189 | 190 | .markdown-body a { 191 | color: #4078c0; 192 | text-decoration: none; 193 | } 194 | 195 | .markdown-body a:hover, 196 | .markdown-body a:active { 197 | text-decoration: underline; 198 | } 199 | 200 | .markdown-body strong { 201 | font-weight: 600; 202 | } 203 | 204 | .markdown-body hr { 205 | height: 0; 206 | margin: 15px 0; 207 | overflow: hidden; 208 | background: transparent; 209 | border: 0; 210 | border-bottom: 1px solid #ddd; 211 | } 212 | 213 | .markdown-body hr::before { 214 | display: table; 215 | content: ""; 216 | } 217 | 218 | .markdown-body hr::after { 219 | display: table; 220 | clear: both; 221 | content: ""; 222 | } 223 | 224 | .markdown-body table { 225 | border-spacing: 0; 226 | border-collapse: collapse; 227 | } 228 | 229 | .markdown-body td, 230 | .markdown-body th { 231 | padding: 0; 232 | } 233 | 234 | .markdown-body h1, 235 | .markdown-body h2, 236 | .markdown-body h3, 237 | .markdown-body h4, 238 | .markdown-body h5, 239 | .markdown-body h6 { 240 | margin-top: 20px; 241 | margin-bottom: 0; 242 | } 243 | 244 | .markdown-body h1 { 245 | font-size: 32px; 246 | font-weight: 600; 247 | } 248 | 249 | .markdown-body h2 { 250 | font-size: 24px; 251 | font-weight: 600; 252 | } 253 | 254 | .markdown-body h3 { 255 | font-size: 20px; 256 | font-weight: 600; 257 | } 258 | 259 | .markdown-body h4 { 260 | font-size: 16px; 261 | font-weight: 600; 262 | } 263 | 264 | .markdown-body h5 { 265 | font-size: 14px; 266 | font-weight: 600; 267 | } 268 | 269 | .markdown-body h6 { 270 | font-size: 12px; 271 | font-weight: 600; 272 | } 273 | 274 | .markdown-body p { 275 | margin-top: 0; 276 | margin-bottom: 10px; 277 | } 278 | 279 | .markdown-body blockquote { 280 | margin: 0; 281 | } 282 | 283 | .markdown-body ul, 284 | .markdown-body ol { 285 | padding-left: 0; 286 | margin-top: 0; 287 | margin-bottom: 0; 288 | } 289 | 290 | .markdown-body ol ol, 291 | .markdown-body ul ol { 292 | list-style-type: lower-roman; 293 | } 294 | 295 | .markdown-body ul ul ol, 296 | .markdown-body ul ol ol, 297 | .markdown-body ol ul ol, 298 | .markdown-body ol ol ol { 299 | list-style-type: lower-alpha; 300 | } 301 | 302 | .markdown-body dd { 303 | margin-left: 0; 304 | } 305 | 306 | .markdown-body code { 307 | font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; 308 | font-size: 12px; 309 | } 310 | 311 | .markdown-body pre { 312 | margin-top: 0; 313 | margin-bottom: 0; 314 | font: 12px Consolas, "Liberation Mono", Menlo, Courier, monospace; 315 | } 316 | 317 | .markdown-body .octicon { 318 | vertical-align: text-bottom; 319 | } 320 | 321 | .markdown-body input { 322 | -webkit-font-feature-settings: "liga" 0; 323 | font-feature-settings: "liga" 0; 324 | } 325 | 326 | .markdown-body::before { 327 | display: table; 328 | content: ""; 329 | } 330 | 331 | .markdown-body::after { 332 | display: table; 333 | clear: both; 334 | content: ""; 335 | } 336 | 337 | .markdown-body>*:first-child { 338 | margin-top: 0 !important; 339 | } 340 | 341 | .markdown-body>*:last-child { 342 | margin-bottom: 0 !important; 343 | } 344 | 345 | .markdown-body a:not([href]) { 346 | color: inherit; 347 | text-decoration: none; 348 | } 349 | 350 | .markdown-body .anchor { 351 | float: left; 352 | padding-right: 4px; 353 | margin-left: -20px; 354 | line-height: 1; 355 | } 356 | 357 | .markdown-body .anchor:focus { 358 | outline: none; 359 | } 360 | 361 | .markdown-body p, 362 | .markdown-body blockquote, 363 | .markdown-body ul, 364 | .markdown-body ol, 365 | .markdown-body dl, 366 | .markdown-body table, 367 | .markdown-body pre { 368 | margin-top: 0; 369 | margin-bottom: 16px; 370 | } 371 | 372 | .markdown-body hr { 373 | height: 0.25em; 374 | padding: 0; 375 | margin: 24px 0; 376 | background-color: #e7e7e7; 377 | border: 0; 378 | } 379 | 380 | .markdown-body blockquote { 381 | padding: 0 1em; 382 | color: #777; 383 | border-left: 0.25em solid #ddd; 384 | } 385 | 386 | .markdown-body blockquote>:first-child { 387 | margin-top: 0; 388 | } 389 | 390 | .markdown-body blockquote>:last-child { 391 | margin-bottom: 0; 392 | } 393 | 394 | .markdown-body kbd { 395 | display: inline-block; 396 | padding: 3px 5px; 397 | font-size: 11px; 398 | line-height: 10px; 399 | color: #555; 400 | vertical-align: middle; 401 | background-color: #fcfcfc; 402 | border: solid 1px #ccc; 403 | border-bottom-color: #bbb; 404 | border-radius: 3px; 405 | box-shadow: inset 0 -1px 0 #bbb; 406 | } 407 | 408 | .markdown-body h1, 409 | .markdown-body h2, 410 | .markdown-body h3, 411 | .markdown-body h4, 412 | .markdown-body h5, 413 | .markdown-body h6 { 414 | margin-top: 24px; 415 | margin-bottom: 16px; 416 | font-weight: 600; 417 | line-height: 1.25; 418 | } 419 | 420 | .markdown-body h1 .octicon-link, 421 | .markdown-body h2 .octicon-link, 422 | .markdown-body h3 .octicon-link, 423 | .markdown-body h4 .octicon-link, 424 | .markdown-body h5 .octicon-link, 425 | .markdown-body h6 .octicon-link { 426 | color: #000; 427 | vertical-align: middle; 428 | visibility: hidden; 429 | } 430 | 431 | .markdown-body h1:hover .anchor, 432 | .markdown-body h2:hover .anchor, 433 | .markdown-body h3:hover .anchor, 434 | .markdown-body h4:hover .anchor, 435 | .markdown-body h5:hover .anchor, 436 | .markdown-body h6:hover .anchor { 437 | text-decoration: none; 438 | } 439 | 440 | .markdown-body h1:hover .anchor .octicon-link, 441 | .markdown-body h2:hover .anchor .octicon-link, 442 | .markdown-body h3:hover .anchor .octicon-link, 443 | .markdown-body h4:hover .anchor .octicon-link, 444 | .markdown-body h5:hover .anchor .octicon-link, 445 | .markdown-body h6:hover .anchor .octicon-link { 446 | visibility: visible; 447 | } 448 | 449 | .markdown-body h1 { 450 | padding-bottom: 0.3em; 451 | font-size: 2em; 452 | border-bottom: 1px solid #eee; 453 | } 454 | 455 | .markdown-body h2 { 456 | padding-bottom: 0.3em; 457 | font-size: 1.5em; 458 | border-bottom: 1px solid #eee; 459 | } 460 | 461 | .markdown-body h3 { 462 | font-size: 1.25em; 463 | } 464 | 465 | .markdown-body h4 { 466 | font-size: 1em; 467 | } 468 | 469 | .markdown-body h5 { 470 | font-size: 0.875em; 471 | } 472 | 473 | .markdown-body h6 { 474 | font-size: 0.85em; 475 | color: #777; 476 | } 477 | 478 | .markdown-body ul, 479 | .markdown-body ol { 480 | padding-left: 2em; 481 | } 482 | 483 | .markdown-body ul ul, 484 | .markdown-body ul ol, 485 | .markdown-body ol ol, 486 | .markdown-body ol ul { 487 | margin-top: 0; 488 | margin-bottom: 0; 489 | } 490 | 491 | .markdown-body li>p { 492 | margin-top: 16px; 493 | } 494 | 495 | .markdown-body li+li { 496 | margin-top: 0.25em; 497 | } 498 | 499 | .markdown-body dl { 500 | padding: 0; 501 | } 502 | 503 | .markdown-body dl dt { 504 | padding: 0; 505 | margin-top: 16px; 506 | font-size: 1em; 507 | font-style: italic; 508 | font-weight: bold; 509 | } 510 | 511 | .markdown-body dl dd { 512 | padding: 0 16px; 513 | margin-bottom: 16px; 514 | } 515 | 516 | .markdown-body table { 517 | display: block; 518 | width: 100%; 519 | overflow: auto; 520 | } 521 | 522 | .markdown-body table th { 523 | font-weight: bold; 524 | } 525 | 526 | .markdown-body table th, 527 | .markdown-body table td { 528 | padding: 6px 13px; 529 | border: 1px solid #ddd; 530 | } 531 | 532 | .markdown-body table tr { 533 | background-color: #fff; 534 | border-top: 1px solid #ccc; 535 | } 536 | 537 | .markdown-body table tr:nth-child(2n) { 538 | background-color: #f8f8f8; 539 | } 540 | 541 | .markdown-body img { 542 | max-width: 100%; 543 | box-sizing: content-box; 544 | background-color: #fff; 545 | } 546 | 547 | .markdown-body code { 548 | padding: 0; 549 | padding-top: 0.2em; 550 | padding-bottom: 0.2em; 551 | margin: 0; 552 | font-size: 85%; 553 | background-color: rgba(0,0,0,0.04); 554 | border-radius: 3px; 555 | } 556 | 557 | .markdown-body code::before, 558 | .markdown-body code::after { 559 | letter-spacing: -0.2em; 560 | content: "\00a0"; 561 | } 562 | 563 | .markdown-body pre { 564 | word-wrap: normal; 565 | } 566 | 567 | .markdown-body pre>code { 568 | padding: 0; 569 | margin: 0; 570 | font-size: 100%; 571 | word-break: normal; 572 | white-space: pre; 573 | background: transparent; 574 | border: 0; 575 | } 576 | 577 | .markdown-body .highlight { 578 | margin-bottom: 16px; 579 | } 580 | 581 | .markdown-body .highlight pre { 582 | margin-bottom: 0; 583 | word-break: normal; 584 | } 585 | 586 | .markdown-body .highlight pre, 587 | .markdown-body pre { 588 | padding: 16px; 589 | overflow: auto; 590 | font-size: 85%; 591 | line-height: 1.45; 592 | background-color: #f7f7f7; 593 | border-radius: 3px; 594 | } 595 | 596 | .markdown-body pre code { 597 | display: inline; 598 | max-width: auto; 599 | padding: 0; 600 | margin: 0; 601 | overflow: visible; 602 | line-height: inherit; 603 | word-wrap: normal; 604 | background-color: transparent; 605 | border: 0; 606 | } 607 | 608 | .markdown-body pre code::before, 609 | .markdown-body pre code::after { 610 | content: normal; 611 | } 612 | 613 | .markdown-body .pl-0 { 614 | padding-left: 0 !important; 615 | } 616 | 617 | .markdown-body .pl-1 { 618 | padding-left: 3px !important; 619 | } 620 | 621 | .markdown-body .pl-2 { 622 | padding-left: 6px !important; 623 | } 624 | 625 | .markdown-body .pl-3 { 626 | padding-left: 12px !important; 627 | } 628 | 629 | .markdown-body .pl-4 { 630 | padding-left: 24px !important; 631 | } 632 | 633 | .markdown-body .pl-5 { 634 | padding-left: 36px !important; 635 | } 636 | 637 | .markdown-body .pl-6 { 638 | padding-left: 48px !important; 639 | } 640 | 641 | .markdown-body .full-commit .btn-outline:not(:disabled):hover { 642 | color: #4078c0; 643 | border: 1px solid #4078c0; 644 | } 645 | 646 | .markdown-body kbd { 647 | display: inline-block; 648 | padding: 3px 5px; 649 | font: 11px Consolas, "Liberation Mono", Menlo, Courier, monospace; 650 | line-height: 10px; 651 | color: #555; 652 | vertical-align: middle; 653 | background-color: #fcfcfc; 654 | border: solid 1px #ccc; 655 | border-bottom-color: #bbb; 656 | border-radius: 3px; 657 | box-shadow: inset 0 -1px 0 #bbb; 658 | } 659 | 660 | .markdown-body :checked+.radio-label { 661 | position: relative; 662 | z-index: 1; 663 | border-color: #4078c0; 664 | } 665 | 666 | .markdown-body .task-list-item { 667 | list-style-type: none; 668 | } 669 | 670 | .markdown-body .task-list-item+.task-list-item { 671 | margin-top: 3px; 672 | } 673 | 674 | .markdown-body .task-list-item input { 675 | margin: 0 0.2em 0.25em -1.6em; 676 | vertical-align: middle; 677 | } 678 | 679 | .markdown-body hr { 680 | border-bottom-color: #eee; 681 | } 682 | -------------------------------------------------------------------------------- /docs/content.md: -------------------------------------------------------------------------------- 1 | # BRAID 2 | 3 | Braid is a single-import module for Python 3 that comprises a sequencer and musical notation system for monophonic MIDI synths. Its emphasis is on interpolation, polyrhythms, phasing, and entrainment. 4 | 5 | Braid can be downloaded from its [GitHub repository](https://github.com/brianhouse/braid/releases). 6 | 7 | It was developed by [Brian House](https://brianhouse.net). 8 | 9 | 10 | ## Contents 11 | 12 | 1. [Goals](#goals) 13 | 1. [Installation](#installation) 14 | 1. [Tutorial](#tutorial) 15 | 1. [Prerequisites](#prereqs) 16 | 1. [Hello World](#hello) 17 | 1. [Notes and `Thread.chord`](#notes) 18 | 1. [`Thread.pattern`, part 1](#pattern_1) 19 | 1. [`Thread.pattern`, part 2](#pattern_2) 20 | 1. [`Thread.pattern`, part 3](#pattern_3) 21 | 1. [`Thread.velocity` and `Thread.grace`](#velocity) 22 | 1. [`Thread.phase`](#phase) 23 | 1. [`Thread.rate`](#rate) 24 | 1. [Tweening](#tweens) 25 | 1. [Signals](#signals) 26 | 1. [Tweening rate and sync](#sync) 27 | 1. [Triggers](#triggers) 28 | 1. [MIDI devices and properties](#devices) 29 | 1. [Adding properties](#properties) 30 | 1. [Customizing MIDI behavior](#custom) 31 | 1. [Reference](#reference) 32 | 1. [Glossary](#glossary) 33 | 1. [Global functions](#functions) 34 | 1. [Symbols](#symbols) 35 | 1. [Scales](#scales) 36 | 1. [Signals](#signals) 37 | 38 | 39 | ## Goals 40 | 41 | - **Idiosyncracy** 42 | Braid is a domain-specific language for a very specific set of concerns, namely my interest in gradually evolving rhythmic relationships and music with a relationship to data. 43 | 44 | - **Limited scope** 45 | Braid is MIDI-based, it's monophonic, and it's only a sequencer, not a synthesizer. It's intended to be used with things like the [Meeblip](https://meeblip.com/) and the [Korg Volca](http://i.korg.com/volcaseries) series, but you can wire it into a DAW, too. 46 | 47 | - **Integrates with Python** 48 | I find specialized development environments frustrating, as they limit what's possible to their own sandbox. Braid is just a python module, and as such can be used within other python projects. This is the source of much of its usefullness and power (particularly when it comes to working with data). 49 | 50 | - **Livecoding?** 51 | Maybe. Normally you'd include braid in a script and execute it, but you can also run it in the python interpreter, and that opens up some additional possibilities for exploration and improvisation. Perhaps this could be expanded on with something like jupyter into a full-fledged livecoding environment. 52 | 53 | 54 | #### A note on names 55 | 56 | This framework is called Braid, and the fundamental objects are called _threads_—a thread corresponds to a hardware or software monosynth, and refers to the temporal operations of Braid through which threads can come in and out of sync. This is not a thread in the programming sense (in that respect Braid is single-threaded). 57 | 58 | 59 | ## Installation 60 | 61 | You'll need to have Python 3 installed—if you're using macOS, I recommend doing so with Homebrew. Tested with python 3.7. 62 | 63 | To install (or update) Braid via the terminal: 64 | `pip3 install git+git://github.com/brianhouse/braid --user --upgrade` 65 | 66 | ## Tutorial 67 | 68 | ### Prerequisites 69 | 70 | Braid is, fundamentally, an extension to Python 3. This documentation won't cover python usage and syntax—for that, look [here](https://docs.python.org/3/tutorial/). Most of the power of Braid comes from the fact that it can be interleaved with other python code. Such possibilities are left to the practitioner, or at least out of this documentation. 71 | 72 | Additionally, this documentation assumes a general knowledge of MIDI. 73 | 74 | If you don't know what you're doing with python and the terminal but you've gotten this far, follow the instructions for saving a Braid "Hello World" script below. Then in the Finder, right-click that python file, and open it using the latest version of IDLE, which should appear as one of your choices. You can then use IDLE's built-in text editor to write, save, and run ("Run->Run Module") Braid scripts. 75 | 76 | 77 | ### Hello World 78 | 79 | Any MIDI software or hardware device you have running should more or less work with Braid to make sounds. If you are on macOS, to simplify things download and run [this simple MIDI bridge app](http://brianhouse.net/download/general_MIDI_bridge.app.zip) which will let you use General MIDI for the purposes of this documentation (make sure no other MIDI devices are running before launching the app, and launch it before starting Braid). 80 | 81 | To begin working with Braid, create a new file in your favorite text editor (such as Sublime Text). Create a *thread*—the fundamental object of Braid—and start it: 82 | 83 | ```python 84 | from braid import * 85 | 86 | t = Thread(1) # create a thread with MIDI channel 87 | t.pattern = C, C, C, C # add a pattern 88 | t.start() # start it 89 | 90 | play() # don't forget this 91 | ``` 92 | 93 | Save it as `hello_world.py`, and run it with `python3 hello_world.py 0 0`. The (optional) arguments designate the MIDI out and in interfaces to use. 94 | 95 | $ python3 hello_world.py 96 | {{Python 3.7.4 (default, Jul 9 2019, 18:13:23) 97 | [Clang 10.0.1 (clang-1001.0.46.4)] on darwin 98 | Type "help", "copyright", "credits" or "license" for more information.}} 99 | {{MIDI outputs available: ['to general_MIDI_bridge 1', 'to general_MIDI_bridge 2'] 100 | MIDI OUT: to general_MIDI_bridge 1 101 | MIDI IN: from general_MIDI_bridge 1 102 | Loaded synths 103 | Braid started 104 | Playing}} 105 | 106 | That's it! You should be hearing the steady pulse of progress. 107 | 108 | 109 | ### Top-level controls 110 | 111 | You can start and stop individual threads, with `a_thread.start()` and `a_thread.stop()`, which essentially behave like a mute button. 112 | 113 | Braid also has some universal playback controls. When Braid launches, it is automatically in play mode. Use `pause()` to mute everything, and `play()` to get it going again. If you use `stop()`, it will stop all threads, so you'll need to start them up again individually. `clear()` just stops the threads, but Braid itself is still going and if you start a thread it will sound right away. 114 | 115 | _Advanced note_: If you're doing a lot of livecoding, it's easy to create a new thread with the same name as an old one, and this can lead to orphan threads that you hear but can't reference. Use `stop()` or `clear()` to silence these. 116 | 117 | Try it now: 118 | 119 | ```python 120 | clear() 121 | ``` 122 | 123 | 124 | ### Notes and `chord` 125 | 126 | Start a thread 127 | 128 | ```python 129 | t = Thread(1) # create a thread on channel 1 130 | t.start() 131 | ``` 132 | 133 | MIDI pitch value can be specified by MIDI number or with note-name aliases between C0 and B8. C is an alias for C4, likewise for the rest of the middle octave 134 | 135 | ```python 136 | t.pattern = C, C, C, C 137 | ``` 138 | 139 | is the same as 140 | 141 | ```python 142 | t.pattern = 60, 60, 60, 60 143 | ``` 144 | 145 | 0s simply sustain (no MIDI sent) 146 | 147 | ```python 148 | t.pattern = C, 0, C, C 149 | ``` 150 | 151 | Rests (explicit MIDI note-offs) are specified with a Z 152 | 153 | ```python 154 | t.pattern = C, Z, C, Z 155 | ``` 156 | 157 | By default, there is no specified chord. But if there is one, notes can be specified by scale degree 158 | 159 | ```python 160 | t.chord = C4, MAJ 161 | t.pattern = 1, 3, 5, 7 162 | ``` 163 | 164 | Negative numbers designate the octave below 165 | 166 | ```python 167 | t.pattern = -5, -7, 1, 5 168 | ``` 169 | 170 | A chord consists of a root note and a scale. For example, `C, MAJ` is a major scale built off of C4. That means `1, 2, 3, 4, 5` is the equivalent of `C4, D4, E4, F4, G4`. But behind the scenes, it's specified like this: `Scale([0, 2, 4, 5, 7, 9, 11])`. Here's the [list](#scales) of built-in scales. 171 | 172 | Custom scales can be generated with the following syntax, where numbers are chromatic steps from the root 173 | 174 | ```python 175 | whole_tone_scale = Scale([0, 2, 4, 6, 8, 10]) 176 | ``` 177 | 178 | R specifies a random note in the scale 179 | 180 | ```python 181 | t.chord = C4, whole_tone_scale 182 | t.pattern = 1, R, R, -6 183 | ``` 184 | 185 | Grace notes are specified by using floats 186 | 187 | ```python 188 | t.pattern = 1, 1., 1., 1. 189 | ``` 190 | 191 | Use the g function to create a grace note on note specified with a symbol 192 | 193 | ```python 194 | t.chord = None 195 | t.pattern = C, g(C), g(C), g(C) 196 | ``` 197 | 198 | 199 | ### `Thread.pattern`, part 1 200 | 201 | Start a thread with a pattern 202 | 203 | ```python 204 | t = Thread(1) 205 | t.chord = C, DOR 206 | t.pattern = 1, 1, 1, 1 207 | t.start() 208 | ``` 209 | 210 | Once started, a thread repeats its pattern. Each repetition is called a *cycle*. Each cycle is subdivided evenly by the **steps** in the pattern. 211 | 212 | ```python 213 | t.pattern = 1, 0, 1, 0 # 4/4 214 | t.pattern = 1, 0, 1 # 3/4 215 | t.pattern = 1, 1, 0, 1, 1, 0, 1 # 7/8 216 | ``` 217 | 218 | Each step of a pattern can be a note, but it can also be a subdivision 219 | 220 | ```python 221 | t.pattern = 1, [1, 1], 1, 1 222 | t.pattern = 1, [1, 1], 1, [1, 1, 1] 223 | ``` 224 | 225 | ...or a subdivision of subdivisions, ad finitum 226 | 227 | ```python 228 | t.pattern = 1, [2, [1., 1.]], [3, [2, 1], 1.], [5, [4., 3.]] 229 | ``` 230 | 231 | So brackets indicate subdivisions. Parens, however, indicate a choice. 232 | 233 | ```python 234 | t.pattern = 1, (2, 3, 4), 1, 1 235 | ``` 236 | 237 | Brackets and parens can be combined to create intricate markov chains 238 | 239 | ```python 240 | tempo(132) # set the universal tempo 241 | d = Thread(10) # channel 10 is MIDI for drums 242 | 243 | d.pattern = [([K, H], [K, K]), (K, O)], (H, [H, K]), (S, [S, (O, K), 0, g(S)]), [[H, H], ([H, H], O, [g(S), g(S), g(S), g(S)])] # K, S, H, O are built-in aliases for 36, 38, 42, 46 244 | d.start() 245 | ``` 246 | 247 | Patterns are python lists, so they can be manipulated as such 248 | 249 | ```python 250 | d.pattern = [K, [O, H]] * 4 251 | d.pattern[2] = S 252 | d.pattern[6] = S 253 | d.pattern[6] = [(S, [S, K])] 254 | 255 | d.pattern.reverse() 256 | ``` 257 | 258 | 259 | ### `Thread.pattern`, part 2 260 | 261 | There are additional functions for working with rhythms. For example, euclidean rhythms can be generated with the euc function 262 | 263 | ```python 264 | tempo(132) 265 | d = Thread(10) 266 | d.start() 267 | 268 | steps = 7 269 | pulses = 3 270 | note = K 271 | d.pattern = euc(steps, pulses, note) # [K, 0, K, 0, K, 0, 0] 272 | ``` 273 | 274 | Adding a pattern to an existing pattern fills any 0s with the new pattern 275 | 276 | ```python 277 | d.pattern.add(euc(7, 5, H)) # [K, H, K, H, K, 0, H] 278 | ``` 279 | 280 | XOR'ing a pattern to an existing pattern adds it, but turns any collisions into 0s 281 | 282 | ```python 283 | d.pattern.xor([1, 1, 0, 0, 0, 0, 0]) # [0, 0, K, H, K, 0, H] 284 | ``` 285 | 286 | These can be done even if the patterns are different lengths, to create crossrhythms 287 | 288 | ```python 289 | d.pattern = [K, K] * 2 290 | d.pattern.add([H, H, H, H, H]) 291 | ``` 292 | 293 | Patterns can also be blended 294 | 295 | ```python 296 | d.pattern = blend([K, K, K, K], [S, S, S, S]) # this is probabilistic and will be different every time! 297 | ``` 298 | 299 | same as 300 | 301 | ```python 302 | d.pattern = K, K, K, K 303 | d.pattern.blend([S, S, S, S]) 304 | ``` 305 | 306 | blend can take a balance argument, where 0 is fully pattern A, and 1 is fully pattern B. 307 | 308 | ```python 309 | d.pattern = blend([K, K, K, K], [S, S, S, S], 0.2) # more kicks, less snare 310 | ``` 311 | 312 | 313 | ### `Thread.pattern`, part 3 314 | 315 | Additionally, any given step in a pattern may also be a function. This function should return a note value. 316 | 317 | ```python 318 | t = Thread(1) 319 | t.chord = D, PRG 320 | 321 | def x(): 322 | return choice([1, 3, 5, 7]) 323 | 324 | t.pattern = [x] * 8 325 | 326 | t.start() 327 | ``` 328 | 329 | This is particularly useful for manipulating synth parameters at each step (see [below](#devices)). In this case, creating a wrapped function allows the actual note value to be passed as a parameter. 330 | 331 | ```python 332 | t = VolcaKick(1) 333 | 334 | def k(n): 335 | def f(t): 336 | t.pulse_colour = 127 337 | t.pulse_level = 127 338 | t.tone = 40 339 | t.amp_attack = 0 340 | t.amp_decay = 80 341 | t.resonator_pitch = 0 342 | return n 343 | return f 344 | 345 | def s(n): 346 | def f(t): 347 | t.pulse_colour = 127 348 | t.pulse_level = 127 349 | t.tone = 60 350 | t.amp_attack = 0 351 | t.amp_decay = 20 352 | t.resonator_pitch = 34 353 | return n 354 | return f 355 | 356 | t.pattern = k(1), k(3), s(20), k(1) # custom properties for k and s notes 357 | t.start() 358 | ``` 359 | 360 | 361 | 362 | 363 | ### `Thread.velocity` and `Thread.grace` 364 | 365 | All threads come with some properties built-in. We've seen [`chord`](#notes) already. 366 | 367 | ```python 368 | t = Thread(10) 369 | t.chord = C, MAJ 370 | t.pattern = 1, 1., 1, 1. 371 | t.start() 372 | ``` 373 | 374 | There is also, of course, `velocity` 375 | 376 | ```python 377 | t.velocity = 0.5 378 | ``` 379 | 380 | and `grace` is a percentage of velocity, to control the depth of the grace notes 381 | 382 | ```python 383 | t.velocity = 1.0 384 | t.grace = .45 385 | ``` 386 | 387 | 388 | ### `Thread.phase` 389 | 390 | Consider the following: 391 | 392 | ```python 393 | t1 = Thread(10) 394 | t1.chord = 76, CHR # root note is "Hi Wood Block" 395 | 396 | t2 = Thread(10) 397 | t2.chord = 77, CHR # root note is "Lo Wood Block" 398 | 399 | t1.pattern = [1, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0] # thanks Steve 400 | t2.pattern = t1.pattern 401 | 402 | t1.start() 403 | t2.start(t1) # t1 as argument 404 | ``` 405 | 406 | Note that in this example, `t2` takes `t1` as an argument. This ensures that t2 will start in sync with t1. Otherwise, t1 and t2 will start at arbitrary times, which may not be desirable. 407 | 408 | However, each thread also has a `phase` property that allows us to control the relative phase of threads deliberately. Phase goes from 0-1 and indicates how much of the cycle the pattern is offset. 409 | 410 | ```python 411 | t2.phase = 1/12 # adjust phase by one subdivision 412 | t2.phase = 3/12 413 | t2.phase = 7/12 414 | ``` 415 | 416 | 417 | 418 | ### `Thread.rate` 419 | 420 | As we've already used it, the `tempo()` function sets the universal BPM (or at least the equivalent BPM if cycles were in 4/4 time). Braid silently keeps track of cycles at this tempo. By default, the cycles of each thread match this reference. We just saw how `phase` can offset the patterns of a thread—it does this in relation to the reference cycle. 421 | 422 | Likewise, individual threads can also cycle at their own `rate`. The `rate` property of each thread is a multiplier of the reference cycles—0.5 is twice as slow, 2 is twice as fast. 423 | 424 | ```python 425 | t1 = Thread(1) 426 | t1.pattern = C, C, C, C 427 | t1.start() 428 | 429 | t2 = Thread(2) 430 | t2.pattern = G, G, G, G 431 | t2.start(t1) # keep in phase 432 | 433 | t2.rate = 1/2 # half-speed! 434 | ``` 435 | 436 | Notice that depending on when you hit return, changing the rate can make threads go out of sync (similar to how starting threads at different times puts them out of phase). The way to get around this is to make sure it changes on a cycle edge. For this, use a [trigger](#triggers): 437 | 438 | ```python 439 | t2.stop() 440 | t2.start(t1) 441 | def x(): t2.rate = 0.5 # one-line python function 442 | ... # hit return twice 443 | t2.trigger(x) # executes x at the beginning of the next cycle 444 | ``` 445 | 446 | If you're working with scripts, using triggers like this isn't necessary, as things will execute simultaneously. 447 | 448 | 449 | 450 | 451 | ### Tweening 452 | 453 | Now for the fun part. Any property on a thread can be **tweened**—that is, interpolated between two values over time (yes, the term is borrowed from Flash). 454 | 455 | This is done simply by assigning a `tween()` function to the property instead of a value. `tween()` has two required arguments: the target value, and the number of cycles to get there. (A transition function can also be specified, more on that below.) Braid will then automatically tween from the current value to the target value, starting with the next cycle. 456 | 457 | ```python 458 | p1 = Thread(1) 459 | p2 = Thread(2) 460 | 461 | pp = [E4, Gb4, B4, Db5], [D5, Gb4, E4, Db5], [B4, Gb4, D5, Db5] 462 | p1.pattern = p2.pattern = pp 463 | 464 | p1.start(); p2.start(p1) # two commands, one line 465 | 466 | p2.phase = tween(1/12, 4.0) # take four cycles to move one subdivision 467 | ``` 468 | 469 | All properties on a thread can be tweened. Device specific MIDI parameters move stepwise between ints within the range 0-127 (see [below](#devices)). `rate`, `phase`, `velocity`, `grace` change continuously over float values. `chord` will probabilistically waver between the current value and the target value. `pattern` will perform a blend between the current and target patterns on each cycle, with the balance shifting from one to the other. 470 | 471 | ```python 472 | t = Thread(10) 473 | t.start() 474 | t.pattern = K, K, S, [0, 0, 0, K] 475 | t.pattern = tween([[K, K], [S, 0, K, 0], [0, K], [S, K, 0, K]], 8) 476 | 477 | # or: 478 | 479 | t.pattern = euc(8, 5, 43) 480 | t.pattern = tween(euc(8, 6, 50), 8) 481 | t.pattern = tween(euc(8, 5, 43), 8) 482 | ``` 483 | 484 | When a tween completes, it can trigger a function, using the `on_end` parameter. The following example tweens the phase of Thread `t` over 8 cycles, and then stops the thread (Note the lack of parentheses around `t.stop`—we want the thread to execute the function at the end of the tween, not during this declaration!). 485 | 486 | ```python 487 | t.phase = tween(0.5, 8, on_end=t.stop) 488 | ``` 489 | 490 | 491 | 492 | ### Signals 493 | 494 | Tweens can take an additional property, called a signal. This is any function that takes a float value from 0 to 1 and return another value from 0 to 1—a nonlinear transition function when you don't want to go from A to B in a straight line. (Yes, Flash again). 495 | 496 | Built-in signals: `linear` (default), `ease_in`, `ease_out`, `ease_in_out`, `ease_out_in` 497 | 498 | ```python 499 | t = Thread(1) 500 | t.chord = D, DOR 501 | t.pattern = [1, 3, 5, 7] * 4 502 | t.start() 503 | 504 | t.chord = tween((E, MAJ), 8, ease_in_out()) 505 | t.chord = tween((E, MAJ), 8, ease_out_in()) 506 | ``` 507 | 508 | Since signals are just functions, you can write your own in Python. `ease_out`, for example, is just 509 | 510 | ```python 511 | def ease_out(pos): 512 | pos = clamp(pos) 513 | return (pos - 1)**3 + 1 514 | ``` 515 | 516 | To view a graphic representation of the function, plot it. 517 | 518 | ```python 519 | plot(ease_out) 520 | ``` 521 | 522 | You can also convert _any_ timeseries data into a signal function using `timeseries()`. You might use this to tween velocity over an entire composition, for example, or for data sonification. 523 | 524 | ```python 525 | data = 0, 0, 1, 0.8, 1, 0.2, 0, 0.4, 0.8, 1 # arbitrary timseries 526 | f = timeseries(data) 527 | plot(f) 528 | 529 | t = Thread(1) 530 | t.chord = D, SUSb9 531 | t.pattern = [1, 2, 3, 4] * 4 532 | t.start() 533 | 534 | t.velocity = 0.0 # sets the lower bound of the range to 0.0 535 | t.velocity = tween(1.0, 24, f) # sets the uppper bound of the range to 1.0, and applies the signal shape over 24 cycles 536 | ``` 537 | 538 | Likewise, you can specify a function with breakpoints using `breakpoints()`. Each breakpoint is specified with an x,y coordinate system—it doesn't matter what the range and domain are, as it will be normalized. Additionally, a signal shape can be specified for each breakpoint transition, which allows complex curves and transitions. 539 | 540 | ```python 541 | f = breakpoints( 542 | [0, 0], 543 | [2, 0], 544 | [8, 1, ease_in_out()], 545 | [13, 0, ease_in_out()], 546 | [20, 3, ease_in_out()], 547 | [24, 0, ease_out()], 548 | [27, 1, ease_in_out()], 549 | [28.5, 0, ease_out()], 550 | [37.5, 4, ease_in_out()], 551 | [48, 0, ease_out()] 552 | ) 553 | f = breakpoints(data) 554 | plot(f) 555 | ``` 556 | 557 | 558 | ### Sync, and tweening rate 559 | 560 | Braid does something special when you assign a tween to `Thread.rate`. Ordinarily, if two threads started in sync and one thread tweened its rate, they would inevitably end up out of sync. However, Braid automatically adjusts its tweening function such that threads will remain aligned as best as possible. 561 | 562 | ```python 563 | t1 = Thread(1) 564 | t1.chord = D, SUSb9 565 | t1.pattern = 1, 1, 1, 1 566 | t1.start() 567 | 568 | t2 = Thread(2) 569 | t2.chord = D, SUSb9 570 | t2.pattern = 4, 4, 4, 4 571 | t2.start(t1) 572 | 573 | t2.rate = tween(0.5, 4) 574 | ``` 575 | 576 | As simple as that is, that's probably the most interesting feature of Braid to me, and what give it its name. 577 | 578 | If you _don't_ want this functionality, pass `sync=False` to the thread constructor, and the thread won't try to reconcile itself. 579 | 580 | ```python 581 | t = Thread(1, sync=False) 582 | ``` 583 | 584 | ### Triggers 585 | 586 | You can sequence in Braid using triggers. A trigger consists of a function, the number of *complete* cycles to wait before executing it, and whether or not (and how many times) to repeat. Triggers can be added to individual threads (`Thread.trigger()`), which then reference the thread's cycle, or they can use the universal `trigger()` function, which reference the universal (silent) cycles (as we've seen with `Thread.rate` and `Thread.phase`, these can be different). 587 | 588 | Triggers execute at the edge between cycles. 589 | 590 | #### Thread Triggers 591 | 592 | ```python 593 | t = Thread(1) 594 | t.chord = D, SUSb9 595 | t.pattern = 1, 1, 1, 1 596 | t.start() 597 | 598 | def x(): t.pattern = 4, 4, 4, 4 # one-line python function 599 | ... 600 | t.trigger(x) # triggers x at the end of the current cycle 601 | t.trigger(x, 1) # triggers x at the end of the first complete cycle 602 | t.trigger(x, 4) # triggers x at the end of the fourth complete cycle 603 | ``` 604 | 605 | You might want to reuse the same triggered function with different threads. This is facilitated by including an argument in the function definition which will be passed the thread that triggered it. 606 | 607 | ```python 608 | t1 = Thread(1) 609 | t1.chord = D, SUSb9 610 | t1.pattern = 1, 1, 1, 1 611 | t1.start() 612 | 613 | t2 = Thread(2) 614 | t2.chord = D, SUSb9 615 | t2.pattern = 4, 4, 4, 4 616 | t2.start(t1) 617 | 618 | def x(t): t.pattern = R, R, R, R # generic 't' argument 619 | ... 620 | t1.trigger(x, 2) 621 | t2.trigger(x, 2) # same function 622 | ``` 623 | 624 | Using a third argument, triggers can be repeated infinitely or for a set number of times. 625 | 626 | ```python 627 | t.trigger(x, 4, 2) # trigger x after 4 cycles and after 8 cycles 628 | t.trigger(y, 6, True) # trigger x every 6 cycles 629 | ``` 630 | 631 | Also: 632 | 633 | ```python 634 | t.trigger(y, 0, True) # nope 635 | 636 | t.trigger(y) # you probably wanted to do this 637 | t.trigger(y, 1, True) 638 | ``` 639 | 640 | To cancel all triggers on a thread, pass `False`. 641 | 642 | ```python 643 | t.trigger(False) 644 | ``` 645 | 646 | To cancel any triggers on a thread that are repeating infinitely, pass `repeat=False` without other arguments. 647 | 648 | ```python 649 | t.trigger(repeat=False) 650 | ``` 651 | 652 | #### Universal Triggers 653 | 654 | For universal triggers, no thread argument can be supplied to the trigger function. And universal triggers operate via the underlying cycle at the global tempo. Otherwise, they are the same as thread triggers, and are particularly useful for sets of changes, as defined in larger functions, or universal functions. 655 | 656 | ```python 657 | t1 = Thread(1) 658 | t1.chord = D, SUSb9 659 | t1.pattern = 1, 1, 1, 1 660 | t1.start() 661 | 662 | t2 = Thread(2) 663 | t2.chord = D, SUSb9 664 | t2.pattern = 4, 4, 4, 4 665 | t2.start(t1) 666 | 667 | def x(): 668 | ... tempo(tempo() * 1.3) # calling tempo without arguments returns the current value 669 | ... t1.chord = D2, SUSb9 670 | ... t1.phase = 1/8 671 | ... t1.pattern = t2.pattern = R, R, R, R 672 | trigger(x, 2) 673 | ``` 674 | 675 | 676 | ### MIDI devices and properties 677 | 678 | Braid is designed to work with hardware monosynths. Thus far, the only actual MIDI output we've been sending are MIDI notes. But CC values from devices are mapped directly to thread properties. 679 | 680 | Devices are represented in Braid as extensions to the thread object. To create a custom thread, use the `make()` function. `make()` is passed a dictionary with property names mapped to MIDI CC channels. 681 | 682 | ```python 683 | Voltron = make({'attack': 54, 'decay': 53, 'filter_cutoff': 52, 'pulse_width': 51}) 684 | ``` 685 | 686 | Now, Voltron can be used like any thread, but it will also have the specified CC values that can be set, tweened, etc. 687 | 688 | ```python 689 | t = Voltron(1) 690 | t.pattern = [1, 2, 3, 5] * 4 691 | t.filter_cutoff = 0 692 | t.filter_cutoff = tween(127, 8) 693 | t.start() 694 | ``` 695 | 696 | Since you'll probably be using the same MIDI devices all the time, and it is tedious to specify this each time you run Braid (especially with large numbers of controls), Braid also automatically loads custom thread types from the `synths.yaml` file in the root directory. 697 | 698 | Note: A second dictionary can be passed to `make()` as an additional parameter with property names mapped to default MIDI values. 699 | 700 | 701 | ### Customizing MIDI behavior 702 | 703 | See `custom.py` in the examples. 704 | 705 | 706 | ### Adding properties 707 | 708 | In some cases, you may want to use a reference property that does not directly affect a thread itself or send any MIDI data—a thread-specific variable that can be tweened as though it were a property, in order to guide other processes. 709 | 710 | ```python 711 | t = Thread(1) 712 | t.add('ref') 713 | t.ref = 0 714 | t.ref = tween(1.0, 8) 715 | ``` 716 | 717 | 718 | ## Reference 719 | 720 | ### Glossary 721 | - `Thread` 722 | - `cycle` 723 | - `step` 724 | - `trigger` 725 | 726 | ### Global functions 727 | - `log_midi(True|False)` Choose whether to see MIDI output (default: False) 728 | - `midi_out.interface = int` Change MIDI interface for output (zero-indexed) 729 | - `midi_in.interface = int` Change MIDI interface for input (zero-indexed) 730 | - `midi_out.scan()` Scan MIDI interfaces 731 | - `Thread(int channel)` Create a Thread on the specified MIDI channel 732 | - `Scale([ints])` Create a Scale with a list of ints corresponding to half-steps from root (0) 733 | - `play()` 734 | - `pause()` 735 | - `stop()` 736 | - `clear()` 737 | - `tempo()` 738 | - `g()` 739 | - `clamp()` 740 | - `plot()` 741 | - `trigger()` 742 | - `random()` 743 | - `choice()` 744 | - `make()` 745 | - `timeseries()` 746 | - `breakpoints()` 747 | 748 | ### Symbols 749 | - `K`, `S`, `H`, `O` 750 | 751 | ### Scales 752 | `CHR` Chromatic, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 753 | `MAJ` Major, 0, 2, 4, 5, 7, 9, 11 754 | `DOM` Dominant, 0, 2, 4, 5, 7, 9, 10 755 | `MIN` Harmonic minor, 0, 2, 3, 5, 7, 8, 11 756 | `MMI` Major-Minor, 0, 2, 4, 5, 6, 9, 11 757 | `PEN` Pentatonic, 0, 2, 5, 7, 10 758 | `SUSb9` Suspended flat 9, 0, 1, 3, 5, 7, 8, 10 759 | `ION` Ionian, 0, 2, 4, 5, 7, 9, 11 760 | `DOR` Dorian, 0, 2, 3, 5, 7, 9, 10 761 | `PRG` Phrygian, 0, 1, 3, 5, 7, 8, 10 762 | `MYX` Myxolydian, 0, 2, 4, 5, 7, 9, 10 763 | `AOL` Aolian, 0, 2, 3, 5, 7, 8, 10 764 | `LOC` Locrian, 0, 1, 3, 5, 6, 8, 10 765 | `BLU` Blues, 0, 3, 5, 6, 7, 10 766 | `SDR` Gamelan Slendro, 0, 2, 5, 7, 9 767 | `PLG` Gamelan Pelog, 0, 1, 3, 6, 7, 8, 10 768 | `JAM` jamz, 0, 2, 3, 5, 6, 7, 10, 11 769 | `DRM` stepwise drums, 0, 2, 7, 14, 6, 10, 3, 39, 31, 13 770 | 771 | ### Signals 772 | `linear` (default) 773 | `ease_in` 774 | `ease_out` 775 | `ease_in_out` 776 | `ease_out_in` 777 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Braid MIDI sequencer 5 | 6 | 7 | 8 | 9 | 11 | 12 | 13 | 14 | 15 | 16 | 115 | 116 | 117 |
118 | 119 |

BRAID

120 | 121 |

Braid is a single-import module for Python 3 that comprises a sequencer and musical notation system for monophonic MIDI synths. Its emphasis is on interpolation, polyrhythms, phasing, and entrainment.

122 | 123 |

Braid can be downloaded from its GitHub repository.

124 | 125 |

It was developed by Brian House.

126 | 127 |

Contents

128 | 129 |
    130 |
  1. Goals
  2. 131 |
  3. Installation
  4. 132 |
  5. Tutorial 133 |
      134 |
    1. Prerequisites
    2. 135 |
    3. Hello World
    4. 136 |
    5. Notes and Thread.chord
    6. 137 |
    7. Thread.pattern, part 1
    8. 138 |
    9. Thread.pattern, part 2
    10. 139 |
    11. Thread.pattern, part 3
    12. 140 |
    13. Thread.velocity and Thread.grace
    14. 141 |
    15. Thread.phase
    16. 142 |
    17. Thread.rate
    18. 143 |
    19. Tweening
    20. 144 |
    21. Signals
    22. 145 |
    23. Tweening rate and sync
    24. 146 |
    25. Triggers
    26. 147 |
    27. MIDI devices and properties
    28. 148 |
    29. Adding properties
    30. 149 |
    31. Customizing MIDI behavior
    32. 150 |
  6. 151 |
  7. Reference 152 |
      153 |
    1. Glossary
    2. 154 |
    3. Global functions
    4. 155 |
    5. Symbols
    6. 156 |
    7. Scales
    8. 157 |
    9. Signals
    10. 158 |
  8. 159 |
160 | 161 |

Goals

162 | 163 |
    164 |
  • Idiosyncracy
    165 | Braid is a domain-specific language for a very specific set of concerns, namely my interest in gradually evolving rhythmic relationships and music with a relationship to data.

  • 166 |
  • Limited scope
    167 | Braid is MIDI-based, it's monophonic, and it's only a sequencer, not a synthesizer. It's intended to be used with things like the Meeblip and the Korg Volca series, but you can wire it into a DAW, too.

  • 168 |
  • Integrates with Python
    169 | I find specialized development environments frustrating, as they limit what's possible to their own sandbox. Braid is just a python module, and as such can be used within other python projects. This is the source of much of its usefullness and power (particularly when it comes to working with data).

  • 170 |
  • Livecoding?
    171 | Maybe. Normally you'd include braid in a script and execute it, but you can also run it in the python interpreter, and that opens up some additional possibilities for exploration and improvisation. Perhaps this could be expanded on with something like jupyter into a full-fledged livecoding environment.

  • 172 |
173 | 174 |

A note on names

175 | 176 |

This framework is called Braid, and the fundamental objects are called threads—a thread corresponds to a hardware or software monosynth, and refers to the temporal operations of Braid through which threads can come in and out of sync. This is not a thread in the programming sense (in that respect Braid is single-threaded).

177 | 178 |

Installation

179 | 180 |

You'll need to have Python 3 installed—if you're using macOS, I recommend doing so with Homebrew. Tested with python 3.7.

181 | 182 |

To install (or update) Braid via the terminal:
183 | pip3 install git+git://github.com/brianhouse/braid --user --upgrade

184 | 185 |

Tutorial

186 | 187 |

Prerequisites

188 | 189 |

Braid is, fundamentally, an extension to Python 3. This documentation won't cover python usage and syntax—for that, look here. Most of the power of Braid comes from the fact that it can be interleaved with other python code. Such possibilities are left to the practitioner, or at least out of this documentation.

190 | 191 |

Additionally, this documentation assumes a general knowledge of MIDI.

192 | 193 |

If you don't know what you're doing with python and the terminal but you've gotten this far, follow the instructions for saving a Braid "Hello World" script below. Then in the Finder, right-click that python file, and open it using the latest version of IDLE, which should appear as one of your choices. You can then use IDLE's built-in text editor to write, save, and run ("Run->Run Module") Braid scripts.

194 | 195 |

Hello World

196 | 197 |

Any MIDI software or hardware device you have running should more or less work with Braid to make sounds. If you are on macOS, to simplify things download and run this simple MIDI bridge app which will let you use General MIDI for the purposes of this documentation (make sure no other MIDI devices are running before launching the app, and launch it before starting Braid).

198 | 199 |

To begin working with Braid, create a new file in your favorite text editor (such as Sublime Text). Create a thread—the fundamental object of Braid—and start it:

200 | 201 |
from braid import *
202 | 
203 | t = Thread(1)               # create a thread with MIDI channel
204 | t.pattern = C, C, C, C      # add a pattern
205 | t.start()                   # start it
206 | 
207 | play()                      # don't forget this
208 | 
209 | 210 |

Save it as hello_world.py, and run it with python3 hello_world.py 0 0. The (optional) arguments designate the MIDI out and in interfaces to use.

211 | 212 |
$ python3 hello_world.py
213 | Python 3.7.4 (default, Jul  9 2019, 18:13:23)
214 | [Clang 10.0.1 (clang-1001.0.46.4)] on darwin
215 | Type "help", "copyright", "credits" or "license" for more information.
216 | MIDI outputs available: ['to general_MIDI_bridge 1', 'to general_MIDI_bridge 2']
217 | MIDI OUT: to general_MIDI_bridge 1
218 | MIDI  IN: from general_MIDI_bridge 1
219 | Loaded synths
220 | Braid started
221 | Playing
222 | 
223 | 224 |

That's it! You should be hearing the steady pulse of progress.

225 | 226 |

Top-level controls

227 | 228 |

You can start and stop individual threads, with a_thread.start() and a_thread.stop(), which essentially behave like a mute button.

229 | 230 |

Braid also has some universal playback controls. When Braid launches, it is automatically in play mode. Use pause() to mute everything, and play() to get it going again. If you use stop(), it will stop all threads, so you'll need to start them up again individually. clear() just stops the threads, but Braid itself is still going and if you start a thread it will sound right away.

231 | 232 |

Advanced note: If you're doing a lot of livecoding, it's easy to create a new thread with the same name as an old one, and this can lead to orphan threads that you hear but can't reference. Use stop() or clear() to silence these.

233 | 234 |

Try it now:

235 | 236 |
clear()
237 | 
238 | 239 |

Notes and chord

240 | 241 |

Start a thread

242 | 243 |
t = Thread(1)   # create a thread on channel 1
244 | t.start()
245 | 
246 | 247 |

MIDI pitch value can be specified by MIDI number or with note-name aliases between C0 and B8. C is an alias for C4, likewise for the rest of the middle octave

248 | 249 |
t.pattern = C, C, C, C
250 | 
251 | 252 |

is the same as

253 | 254 |
t.pattern = 60, 60, 60, 60
255 | 
256 | 257 |

0s simply sustain (no MIDI sent)

258 | 259 |
t.pattern = C, 0, C, C
260 | 
261 | 262 |

Rests (explicit MIDI note-offs) are specified with a Z

263 | 264 |
t.pattern = C, Z, C, Z
265 | 
266 | 267 |

By default, there is no specified chord. But if there is one, notes can be specified by scale degree

268 | 269 |
t.chord = C4, MAJ
270 | t.pattern = 1, 3, 5, 7
271 | 
272 | 273 |

Negative numbers designate the octave below

274 | 275 |
t.pattern = -5, -7, 1, 5
276 | 
277 | 278 |

A chord consists of a root note and a scale. For example, C, MAJ is a major scale built off of C4. That means 1, 2, 3, 4, 5 is the equivalent of C4, D4, E4, F4, G4. But behind the scenes, it's specified like this: Scale([0, 2, 4, 5, 7, 9, 11]). Here's the list of built-in scales.

279 | 280 |

Custom scales can be generated with the following syntax, where numbers are chromatic steps from the root

281 | 282 |
whole_tone_scale = Scale([0, 2, 4, 6, 8, 10])
283 | 
284 | 285 |

R specifies a random note in the scale

286 | 287 |
t.chord = C4, whole_tone_scale
288 | t.pattern = 1, R, R, -6
289 | 
290 | 291 |

Grace notes are specified by using floats

292 | 293 |
t.pattern = 1, 1., 1., 1.
294 | 
295 | 296 |

Use the g function to create a grace note on note specified with a symbol

297 | 298 |
t.chord = None
299 | t.pattern = C, g(C), g(C), g(C)
300 | 
301 | 302 |

Thread.pattern, part 1

303 | 304 |

Start a thread with a pattern

305 | 306 |
t = Thread(1)
307 | t.chord = C, DOR
308 | t.pattern = 1, 1, 1, 1
309 | t.start()
310 | 
311 | 312 |

Once started, a thread repeats its pattern. Each repetition is called a cycle. Each cycle is subdivided evenly by the steps in the pattern.

313 | 314 |
t.pattern = 1, 0, 1, 0              # 4/4
315 | t.pattern = 1, 0, 1                 # 3/4
316 | t.pattern = 1, 1, 0, 1, 1, 0, 1     # 7/8
317 | 
318 | 319 |

Each step of a pattern can be a note, but it can also be a subdivision

320 | 321 |
t.pattern = 1, [1, 1], 1, 1
322 | t.pattern = 1, [1, 1], 1, [1, 1, 1]
323 | 
324 | 325 |

...or a subdivision of subdivisions, ad finitum

326 | 327 |
t.pattern = 1, [2, [1., 1.]], [3, [2, 1], 1.], [5, [4., 3.]]
328 | 
329 | 330 |

So brackets indicate subdivisions. Parens, however, indicate a choice.

331 | 332 |
t.pattern = 1, (2, 3, 4), 1, 1
333 | 
334 | 335 |

Brackets and parens can be combined to create intricate markov chains

336 | 337 |
tempo(132)                  # set the universal tempo
338 | d = Thread(10)              # channel 10 is MIDI for drums
339 | 
340 | d.pattern = [([K, H], [K, K]), (K, O)], (H, [H, K]), (S, [S, (O, K), 0, g(S)]), [[H, H], ([H, H], O, [g(S), g(S), g(S), g(S)])]         # K, S, H, O are built-in aliases for 36, 38, 42, 46
341 | d.start()
342 | 
343 | 344 |

Patterns are python lists, so they can be manipulated as such

345 | 346 |
d.pattern = [K, [O, H]] * 4
347 | d.pattern[2] = S
348 | d.pattern[6] = S
349 | d.pattern[6] = [(S, [S, K])]
350 | 
351 | d.pattern.reverse()
352 | 
353 | 354 |

Thread.pattern, part 2

355 | 356 |

There are additional functions for working with rhythms. For example, euclidean rhythms can be generated with the euc function

357 | 358 |
tempo(132)   
359 | d = Thread(10)
360 | d.start()
361 | 
362 | steps = 7
363 | pulses = 3
364 | note = K
365 | d.pattern = euc(steps, pulses, note)    # [K, 0, K, 0, K, 0, 0]
366 | 
367 | 368 |

Adding a pattern to an existing pattern fills any 0s with the new pattern

369 | 370 |
d.pattern.add(euc(7, 5, H))             # [K, H, K, H, K, 0, H]
371 | 
372 | 373 |

XOR'ing a pattern to an existing pattern adds it, but turns any collisions into 0s

374 | 375 |
d.pattern.xor([1, 1, 0, 0, 0, 0, 0])    # [0, 0, K, H, K, 0, H]
376 | 
377 | 378 |

These can be done even if the patterns are different lengths, to create crossrhythms

379 | 380 |
d.pattern = [K, K] * 2
381 | d.pattern.add([H, H, H, H, H])
382 | 
383 | 384 |

Patterns can also be blended

385 | 386 |
d.pattern = blend([K, K, K, K], [S, S, S, S])   # this is probabilistic and will be different every time!
387 | 
388 | 389 |

same as

390 | 391 |
d.pattern = K, K, K, K
392 | d.pattern.blend([S, S, S, S])
393 | 
394 | 395 |

blend can take a balance argument, where 0 is fully pattern A, and 1 is fully pattern B.

396 | 397 |
d.pattern = blend([K, K, K, K], [S, S, S, S], 0.2)   # more kicks, less snare
398 | 
399 | 400 |

Thread.pattern, part 3

401 | 402 |

Additionally, any given step in a pattern may also be a function. This function should return a note value.

403 | 404 |
t = Thread(1)
405 | t.chord = D, PRG
406 | 
407 | def x():
408 |     return choice([1, 3, 5, 7])
409 | 
410 | t.pattern = [x] * 8
411 | 
412 | t.start()
413 | 
414 | 415 |

This is particularly useful for manipulating synth parameters at each step (see below). In this case, creating a wrapped function allows the actual note value to be passed as a parameter.

416 | 417 |
t = VolcaKick(1)
418 | 
419 | def k(n):
420 |     def f(t):
421 |         t.pulse_colour = 127
422 |         t.pulse_level = 127
423 |         t.tone = 40
424 |         t.amp_attack = 0
425 |         t.amp_decay = 80
426 |         t.resonator_pitch = 0
427 |         return n
428 |     return f
429 | 
430 | def s(n):
431 |     def f(t):    
432 |         t.pulse_colour = 127
433 |         t.pulse_level = 127
434 |         t.tone = 60
435 |         t.amp_attack = 0
436 |         t.amp_decay = 20
437 |         t.resonator_pitch = 34
438 |         return n
439 |     return f
440 | 
441 | t.pattern = k(1), k(3), s(20), k(1)              # custom properties for k and s notes
442 | t.start()
443 | 
444 | 445 |

Thread.velocity and Thread.grace

446 | 447 |

All threads come with some properties built-in. We've seen chord already.

448 | 449 |
t = Thread(10)
450 | t.chord = C, MAJ
451 | t.pattern = 1, 1., 1, 1.
452 | t.start()
453 | 
454 | 455 |

There is also, of course, velocity

456 | 457 |
t.velocity = 0.5
458 | 
459 | 460 |

and grace is a percentage of velocity, to control the depth of the grace notes

461 | 462 |
t.velocity = 1.0
463 | t.grace = .45
464 | 
465 | 466 |

Thread.phase

467 | 468 |

Consider the following:

469 | 470 |
t1 = Thread(10)
471 | t1.chord = 76, CHR  # root note is "Hi Wood Block"
472 | 
473 | t2 = Thread(10)
474 | t2.chord = 77, CHR  # root note is "Lo Wood Block"
475 | 
476 | t1.pattern = [1, 1, 1, 0], [1, 1, 0, 1], [0, 1, 1, 0]   # thanks Steve
477 | t2.pattern = t1.pattern
478 | 
479 | t1.start()
480 | t2.start(t1)            # t1 as argument
481 | 
482 | 483 |

Note that in this example, t2 takes t1 as an argument. This ensures that t2 will start in sync with t1. Otherwise, t1 and t2 will start at arbitrary times, which may not be desirable.

484 | 485 |

However, each thread also has a phase property that allows us to control the relative phase of threads deliberately. Phase goes from 0-1 and indicates how much of the cycle the pattern is offset.

486 | 487 |
t2.phase = 1/12         # adjust phase by one subdivision
488 | t2.phase = 3/12
489 | t2.phase = 7/12
490 | 
491 | 492 |

Thread.rate

493 | 494 |

As we've already used it, the tempo() function sets the universal BPM (or at least the equivalent BPM if cycles were in 4/4 time). Braid silently keeps track of cycles at this tempo. By default, the cycles of each thread match this reference. We just saw how phase can offset the patterns of a thread—it does this in relation to the reference cycle.

495 | 496 |

Likewise, individual threads can also cycle at their own rate. The rate property of each thread is a multiplier of the reference cycles—0.5 is twice as slow, 2 is twice as fast.

497 | 498 |
t1 = Thread(1)
499 | t1.pattern = C, C, C, C
500 | t1.start()
501 | 
502 | t2 = Thread(2)
503 | t2.pattern = G, G, G, G
504 | t2.start(t1)                    # keep in phase
505 | 
506 | t2.rate = 1/2                   # half-speed!    
507 | 
508 | 509 |

Notice that depending on when you hit return, changing the rate can make threads go out of sync (similar to how starting threads at different times puts them out of phase). The way to get around this is to make sure it changes on a cycle edge. For this, use a trigger:

510 | 511 |
t2.stop()
512 | t2.start(t1)
513 | def x(): t2.rate = 0.5          # one-line python function
514 | ...                                 # hit return twice
515 | t2.trigger(x)                   # executes x at the beginning of the next cycle
516 | 
517 | 518 |

If you're working with scripts, using triggers like this isn't necessary, as things will execute simultaneously.

519 | 520 |

Tweening

521 | 522 |

Now for the fun part. Any property on a thread can be tweened—that is, interpolated between two values over time (yes, the term is borrowed from Flash).

523 | 524 |

This is done simply by assigning a tween() function to the property instead of a value. tween() has two required arguments: the target value, and the number of cycles to get there. (A transition function can also be specified, more on that below.) Braid will then automatically tween from the current value to the target value, starting with the next cycle.

525 | 526 |
p1 = Thread(1)
527 | p2 = Thread(2)
528 | 
529 | pp = [E4, Gb4, B4, Db5], [D5, Gb4, E4, Db5], [B4, Gb4, D5, Db5]
530 | p1.pattern = p2.pattern = pp
531 | 
532 | p1.start(); p2.start(p1)            # two commands, one line
533 | 
534 | p2.phase = tween(1/12, 4.0)         # take four cycles to move one subdivision
535 | 
536 | 537 |

All properties on a thread can be tweened. Device specific MIDI parameters move stepwise between ints within the range 0-127 (see below). rate, phase, velocity, grace change continuously over float values. chord will probabilistically waver between the current value and the target value. pattern will perform a blend between the current and target patterns on each cycle, with the balance shifting from one to the other.

538 | 539 |
t = Thread(10)
540 | t.start()
541 | t.pattern = K, K, S, [0, 0, 0, K]
542 | t.pattern = tween([[K, K], [S, 0, K, 0], [0, K], [S, K, 0, K]], 8)
543 | 
544 | # or:
545 | 
546 | t.pattern = euc(8, 5, 43)
547 | t.pattern = tween(euc(8, 6, 50), 8)
548 | t.pattern = tween(euc(8, 5, 43), 8)
549 | 
550 | 551 |

When a tween completes, it can trigger a function, using the on_end parameter. The following example tweens the phase of Thread t over 8 cycles, and then stops the thread (Note the lack of parentheses around t.stop—we want the thread to execute the function at the end of the tween, not during this declaration!).

552 | 553 |
t.phase = tween(0.5, 8, on_end=t.stop)
554 | 
555 | 556 |

Signals

557 | 558 |

Tweens can take an additional property, called a signal. This is any function that takes a float value from 0 to 1 and return another value from 0 to 1—a nonlinear transition function when you don't want to go from A to B in a straight line. (Yes, Flash again).

559 | 560 |

Built-in signals: linear (default), ease_in, ease_out, ease_in_out, ease_out_in

561 | 562 |
t = Thread(1)
563 | t.chord = D, DOR
564 | t.pattern = [1, 3, 5, 7] * 4
565 | t.start()
566 | 
567 | t.chord = tween((E, MAJ), 8, ease_in_out())
568 | t.chord = tween((E, MAJ), 8, ease_out_in())
569 | 
570 | 571 |

Since signals are just functions, you can write your own in Python. ease_out, for example, is just

572 | 573 |
def ease_out(pos):
574 |     pos = clamp(pos)    
575 |     return (pos - 1)**3 + 1
576 | 
577 | 578 |

To view a graphic representation of the function, plot it.

579 | 580 |
plot(ease_out)
581 | 
582 | 583 |

You can also convert any timeseries data into a signal function using timeseries(). You might use this to tween velocity over an entire composition, for example, or for data sonification.

584 | 585 |
data = 0, 0, 1, 0.8, 1, 0.2, 0, 0.4, 0.8, 1     # arbitrary timseries
586 | f = timeseries(data)
587 | plot(f)
588 | 
589 | t = Thread(1)
590 | t.chord = D, SUSb9
591 | t.pattern = [1, 2, 3, 4] * 4
592 | t.start()
593 | 
594 | t.velocity = 0.0                                # sets the lower bound of the range to 0.0
595 | t.velocity = tween(1.0, 24, f)                  # sets the uppper bound of the range to 1.0, and applies the signal shape over 24 cycles
596 | 
597 | 598 |

Likewise, you can specify a function with breakpoints using breakpoints(). Each breakpoint is specified with an x,y coordinate system—it doesn't matter what the range and domain are, as it will be normalized. Additionally, a signal shape can be specified for each breakpoint transition, which allows complex curves and transitions.

599 | 600 |
f = breakpoints(
601 |                 [0, 0],
602 |                 [2, 0],
603 |                 [8, 1, ease_in_out()],
604 |                 [13, 0, ease_in_out()],
605 |                 [20, 3, ease_in_out()],
606 |                 [24, 0, ease_out()],
607 |                 [27, 1, ease_in_out()],
608 |                 [28.5, 0, ease_out()],
609 |                 [37.5, 4, ease_in_out()],
610 |                 [48, 0, ease_out()]
611 |                 )
612 | f = breakpoints(data)
613 | plot(f)
614 | 
615 | 616 |

Sync, and tweening rate

617 | 618 |

Braid does something special when you assign a tween to Thread.rate. Ordinarily, if two threads started in sync and one thread tweened its rate, they would inevitably end up out of sync. However, Braid automatically adjusts its tweening function such that threads will remain aligned as best as possible.

619 | 620 |
t1 = Thread(1)
621 | t1.chord = D, SUSb9
622 | t1.pattern = 1, 1, 1, 1
623 | t1.start()
624 | 
625 | t2 = Thread(2)
626 | t2.chord = D, SUSb9
627 | t2.pattern = 4, 4, 4, 4
628 | t2.start(t1)
629 | 
630 | t2.rate = tween(0.5, 4)
631 | 
632 | 633 |

As simple as that is, that's probably the most interesting feature of Braid to me, and what give it its name.

634 | 635 |

If you don't want this functionality, pass sync=False to the thread constructor, and the thread won't try to reconcile itself.

636 | 637 |
t = Thread(1, sync=False)
638 | 
639 | 640 |

Triggers

641 | 642 |

You can sequence in Braid using triggers. A trigger consists of a function, the number of complete cycles to wait before executing it, and whether or not (and how many times) to repeat. Triggers can be added to individual threads (Thread.trigger()), which then reference the thread's cycle, or they can use the universal trigger() function, which reference the universal (silent) cycles (as we've seen with Thread.rate and Thread.phase, these can be different).

643 | 644 |

Triggers execute at the edge between cycles.

645 | 646 |

Thread Triggers

647 | 648 |
t = Thread(1)
649 | t.chord = D, SUSb9
650 | t.pattern = 1, 1, 1, 1
651 | t.start()
652 | 
653 | def x(): t.pattern = 4, 4, 4, 4         # one-line python function
654 | ...
655 | t.trigger(x)                            # triggers x at the end of the current cycle
656 | t.trigger(x, 1)                         # triggers x at the end of the first complete cycle
657 | t.trigger(x, 4)                         # triggers x at the end of the fourth complete cycle
658 | 
659 | 660 |

You might want to reuse the same triggered function with different threads. This is facilitated by including an argument in the function definition which will be passed the thread that triggered it.

661 | 662 |
t1 = Thread(1)
663 | t1.chord = D, SUSb9
664 | t1.pattern = 1, 1, 1, 1
665 | t1.start()
666 | 
667 | t2 = Thread(2)
668 | t2.chord = D, SUSb9
669 | t2.pattern = 4, 4, 4, 4
670 | t2.start(t1)
671 | 
672 | def x(t): t.pattern = R, R, R, R    # generic 't' argument
673 | ...
674 | t1.trigger(x, 2)
675 | t2.trigger(x, 2)                    # same function
676 | 
677 | 678 |

Using a third argument, triggers can be repeated infinitely or for a set number of times.

679 | 680 |
t.trigger(x, 4, 2)      # trigger x after 4 cycles and after 8 cycles
681 | t.trigger(y, 6, True)   # trigger x every 6 cycles
682 | 
683 | 684 |

Also:

685 | 686 |
t.trigger(y, 0, True)   # nope
687 | 
688 | t.trigger(y)            # you probably wanted to do this
689 | t.trigger(y, 1, True)   
690 | 
691 | 692 |

To cancel all triggers on a thread, pass False.

693 | 694 |
t.trigger(False)
695 | 
696 | 697 |

To cancel any triggers on a thread that are repeating infinitely, pass repeat=False without other arguments.

698 | 699 |
t.trigger(repeat=False)
700 | 
701 | 702 |

Universal Triggers

703 | 704 |

For universal triggers, no thread argument can be supplied to the trigger function. And universal triggers operate via the underlying cycle at the global tempo. Otherwise, they are the same as thread triggers, and are particularly useful for sets of changes, as defined in larger functions, or universal functions.

705 | 706 |
t1 = Thread(1)
707 | t1.chord = D, SUSb9
708 | t1.pattern = 1, 1, 1, 1
709 | t1.start()
710 | 
711 | t2 = Thread(2)
712 | t2.chord = D, SUSb9
713 | t2.pattern = 4, 4, 4, 4
714 | t2.start(t1)
715 | 
716 | def x():
717 | ...     tempo(tempo() * 1.3)                    # calling tempo without arguments returns the current value
718 | ...     t1.chord = D2, SUSb9
719 | ...     t1.phase = 1/8
720 | ...     t1.pattern = t2.pattern = R, R, R, R
721 | trigger(x, 2)
722 | 
723 | 724 |

MIDI devices and properties

725 | 726 |

Braid is designed to work with hardware monosynths. Thus far, the only actual MIDI output we've been sending are MIDI notes. But CC values from devices are mapped directly to thread properties.

727 | 728 |

Devices are represented in Braid as extensions to the thread object. To create a custom thread, use the make() function. make() is passed a dictionary with property names mapped to MIDI CC channels.

729 | 730 |
Voltron = make({'attack': 54, 'decay': 53, 'filter_cutoff': 52, 'pulse_width': 51})
731 | 
732 | 733 |

Now, Voltron can be used like any thread, but it will also have the specified CC values that can be set, tweened, etc.

734 | 735 |
t = Voltron(1)
736 | t.pattern = [1, 2, 3, 5] * 4
737 | t.filter_cutoff = 0
738 | t.filter_cutoff = tween(127, 8)
739 | t.start()
740 | 
741 | 742 |

Since you'll probably be using the same MIDI devices all the time, and it is tedious to specify this each time you run Braid (especially with large numbers of controls), Braid also automatically loads custom thread types from the synths.yaml file in the root directory.

743 | 744 |

Note: A second dictionary can be passed to make() as an additional parameter with property names mapped to default MIDI values.

745 | 746 |

Customizing MIDI behavior

747 | 748 |

See custom.py in the examples.

749 | 750 |

Adding properties

751 | 752 |

In some cases, you may want to use a reference property that does not directly affect a thread itself or send any MIDI data—a thread-specific variable that can be tweened as though it were a property, in order to guide other processes.

753 | 754 |
t = Thread(1)
755 | t.add('ref')
756 | t.ref = 0
757 | t.ref = tween(1.0, 8)
758 | 
759 | 760 |

Reference

761 | 762 |

Glossary

763 | 764 |
    765 |
  • Thread
  • 766 |
  • cycle
  • 767 |
  • step
  • 768 |
  • trigger
  • 769 |
770 | 771 |

Global functions

772 | 773 |
    774 |
  • log_midi(True|False) Choose whether to see MIDI output (default: False)
  • 775 |
  • midi_out.interface = int Change MIDI interface for output (zero-indexed)
  • 776 |
  • midi_in.interface = int Change MIDI interface for input (zero-indexed)
  • 777 |
  • midi_out.scan() Scan MIDI interfaces
  • 778 |
  • Thread(int channel) Create a Thread on the specified MIDI channel
  • 779 |
  • Scale([ints]) Create a Scale with a list of ints corresponding to half-steps from root (0)
  • 780 |
  • play()
  • 781 |
  • pause()
  • 782 |
  • stop()
  • 783 |
  • clear()
  • 784 |
  • tempo()
  • 785 |
  • g()
  • 786 |
  • clamp()
  • 787 |
  • plot()
  • 788 |
  • trigger()
  • 789 |
  • random()
  • 790 |
  • choice()
  • 791 |
  • make()
  • 792 |
  • timeseries()
  • 793 |
  • breakpoints()
  • 794 |
795 | 796 |

Symbols

797 | 798 |
    799 |
  • K, S, H, O
  • 800 |
801 | 802 |

Scales

803 | 804 |

CHR Chromatic, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
805 | MAJ Major, 0, 2, 4, 5, 7, 9, 11
806 | DOM Dominant, 0, 2, 4, 5, 7, 9, 10
807 | MIN Harmonic minor, 0, 2, 3, 5, 7, 8, 11
808 | MMI Major-Minor, 0, 2, 4, 5, 6, 9, 11
809 | PEN Pentatonic, 0, 2, 5, 7, 10
810 | SUSb9 Suspended flat 9, 0, 1, 3, 5, 7, 8, 10
811 | ION Ionian, 0, 2, 4, 5, 7, 9, 11
812 | DOR Dorian, 0, 2, 3, 5, 7, 9, 10
813 | PRG Phrygian, 0, 1, 3, 5, 7, 8, 10
814 | MYX Myxolydian, 0, 2, 4, 5, 7, 9, 10
815 | AOL Aolian, 0, 2, 3, 5, 7, 8, 10
816 | LOC Locrian, 0, 1, 3, 5, 6, 8, 10
817 | BLU Blues, 0, 3, 5, 6, 7, 10
818 | SDR Gamelan Slendro, 0, 2, 5, 7, 9
819 | PLG Gamelan Pelog, 0, 1, 3, 6, 7, 8, 10
820 | JAM jamz, 0, 2, 3, 5, 6, 7, 10, 11
821 | DRM stepwise drums, 0, 2, 7, 14, 6, 10, 3, 39, 31, 13

822 | 823 |

Signals

824 | 825 |

linear (default)
826 | ease_in
827 | ease_out
828 | ease_in_out
829 | ease_out_in

830 | 831 | 832 |
833 | 834 | --------------------------------------------------------------------------------