Skip to content

Instantly share code, notes, and snippets.

@jhw
Last active May 7, 2024 08:09
Show Gist options
  • Save jhw/72d061156d7b7e9da23532453efb7d21 to your computer and use it in GitHub Desktop.
Save jhw/72d061156d7b7e9da23532453efb7d21 to your computer and use it in GitHub Desktop.
Euclidian beat generator rendered with the aid of Sunvox and Radiant Voices
*.pyc
__pycache__
env
tmp

Overview

Euclidian beat generator rendered with the aid of Sunvox and Radiant Voices

https://www.warmplace.ru/soft/sunvox/

https://github.com/metrasynth/radiant-voices

Usage

(env) jhw@Justins-Air 72d061156d7b7e9da23532453efb7d21 % python cli.py
INFO: fetching banks/pico-baseck.zip
INFO: fetching banks/pico-clipping.zip
INFO: fetching banks/pico-complex-waveforms.zip
INFO: fetching banks/pico-default.zip
INFO: fetching banks/pico-dj-raitis-vinyl-cuts.zip
INFO: fetching banks/pico-ib-magnetic-saturation.zip
INFO: fetching banks/pico-legowelt.zip
INFO: fetching banks/pico-nero-bellum.zip
INFO: fetching banks/pico-otto-von-schirach.zip
INFO: fetching banks/pico-pitch-black.zip
INFO: fetching banks/pico-richard-devine.zip
INFO: fetching banks/pico-syntrx.zip
Welcome to the beats CLI ;)
>>> randomise_patches
INFO: 2024-05-04-12-38-41-random-that-affect
>>> export_wav
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1.41M/1.41M [00:00<00:00, 18.3Mframe/s]
SOUND: sundog_sound_deinit() begin
SOUND: sundog_sound_deinit() end
Max memory used: 9568928
Not freed: 9511517
MEMORY CLEANUP: 3712, 984, 2400, 6144, 160, 16, 3112, 4096, 512, 3528, 3528, 65536, 65536, 112, 4096, 5144, 112, 8192, 78336, 8, 640, 128, 512, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 640, 96, 388, 6, 36, 36, 28, 28, 28, 28, 28, 7...
>>> 
- able
- acceptable
- according
- accurate
- action
- active
- actual
- additional
- administrative
- adult
- afraid
- after
- afternoon
- agent
- aggressive
- ago
- airline
- alive
- all
- alone
- alternative
- amazing
- angry
- animal
- annual
- another
- anxious
- any
- apart
- appropriate
- asleep
- automatic
- available
- aware
- away
- background
- basic
- beautiful
- beginning
- best
- better
- big
- bitter
- boring
- born
- both
- brave
- brief
- bright
- brilliant
- broad
- brown
- budget
- business
- busy
- calm
- capable
- capital
- car
- careful
- certain
- chance
- character
- cheap
- chemical
- chicken
- choice
- civil
- classic
- clean
- clear
- close
- cold
- comfortable
- commercial
- common
- competitive
- complete
- complex
- comprehensive
- confident
- connect
- conscious
- consistent
- constant
- content
- cool
- corner
- correct
- crazy
- creative
- critical
- cultural
- curious
- current
- cute
- dangerous
- dark
- daughter
- day
- dead
- dear
- decent
- deep
- dependent
- designer
- desperate
- different
- difficult
- direct
- dirty
- distinct
- double
- downtown
- dramatic
- dress
- drunk
- dry
- due
- each
- east
- eastern
- easy
- economy
- educational
- effective
- efficient
- either
- electrical
- electronic
- embarrassed
- emergency
- emotional
- empty
- enough
- entire
- environmental
- equal
- equivalent
- even
- evening
- every
- exact
- excellent
- exciting
- existing
- expensive
- expert
- express
- extension
- external
- extra
- extreme
- fair
- 'false'
- familiar
- famous
- far
- fast
- fat
- federal
- feeling
- female
- few
- final
- financial
- fine
- firm
- first
- fit
- flat
- foreign
- formal
- former
- forward
- free
- frequent
- fresh
- friendly
- front
- full
- fun
- funny
- future
- game
- general
- glad
- glass
- global
- gold
- good
- grand
- great
- green
- gross
- guilty
- happy
- hard
- head
- healthy
- heavy
- helpful
- high
- his
- historical
- holiday
- home
- honest
- horror
- hot
- hour
- house
- huge
- human
- hungry
- ideal
- ill
- illegal
- immediate
- important
- impossible
- impressive
- incident
- independent
- individual
- inevitable
- informal
- initial
- inner
- inside
- intelligent
- interesting
- internal
- international
- joint
- junior
- just
- key
- kind
- kitchen
- known
- large
- last
- late
- latter
- leading
- least
- leather
- left
- legal
- less
- level
- life
- little
- live
- living
- local
- logical
- lonely
- long
- loose
- lost
- loud
- low
- lower
- lucky
- mad
- main
- major
- male
- many
- massive
- master
- material
- maximum
- mean
- medical
- medium
- mental
- middle
- minimum
- minor
- minute
- mission
- mobile
- money
- more
- most
- mother
- motor
- mountain
- much
- narrow
- nasty
- national
- native
- natural
- nearby
- neat
- necessary
- negative
- neither
- nervous
- new
- next
- nice
- normal
- north
- novel
- numerous
- objective
- obvious
- odd
- official
- old
- only
- open
- opening
- opposite
- ordinary
- original
- other
- otherwise
- outside
- over
- overall
- own
- parking
- particular
- party
- past
- patient
- perfect
- period
- personal
- physical
- plane
- plastic
- pleasant
- plenty
- plus
- political
- poor
- popular
- positive
- possible
- potential
- powerful
- practical
- pregnant
- present
- pretend
- pretty
- previous
- primary
- prior
- private
- prize
- professional
- proof
- proper
- proud
- psychological
- public
- pure
- purple
- quick
- quiet
- rare
- raw
- ready
- real
- realistic
- reasonable
- recent
- red
- regular
- relative
- relevant
- remarkable
- remote
- representative
- resident
- responsible
- rich
- right
- rough
- round
- routine
- royal
- sad
- safe
- salt
- same
- savings
- scared
- sea
- secret
- secure
- select
- senior
- sensitive
- separate
- serious
- several
- severe
- sexual
- sharp
- short
- shot
- sick
- signal
- significant
- silly
- silver
- similar
- simple
- single
- slight
- slow
- small
- smart
- smooth
- soft
- solid
- some
- sorry
- south
- southern
- spare
- special
- specialist
- specific
- spiritual
- square
- standard
- status
- still
- stock
- straight
- strange
- street
- strict
- strong
- stupid
- subject
- substantial
- successful
- such
- sudden
- sufficient
- suitable
- super
- sure
- suspicious
- sweet
- swimming
- tall
- technical
- temporary
- terrible
- that
- then
- these
- thick
- thin
- think
- this
- tight
- time
- tiny
- top
- total
- tough
- traditional
- training
- trick
- 'true'
- typical
- ugly
- unable
- unfair
- unhappy
- unique
- united
- unlikely
- unusual
- upper
- upset
- upstairs
- used
- useful
- usual
- valuable
- various
- vast
- vegetable
- visible
- visual
- warm
- waste
- weak
- weekly
- weird
- west
- western
- what
- which
- white
- whole
- wide
- wild
- willing
- wine
- winter
- wise
- wonderful
- wooden
- work
- working
- worth
- wrong
- yellow
- young
import io, os, zipfile
def list_s3_keys(s3, bucketname, prefix):
paginator=s3.get_paginator("list_objects_v2")
pages=paginator.paginate(Bucket=bucketname,
Prefix=prefix)
keys=[]
for page in pages:
if "Contents" in page:
for obj in page["Contents"]:
keys.append(obj["Key"])
return keys
def list_cached(cachedir):
if not os.path.exists(cachedir):
os.makedirs(cachedir)
cached=[]
for item in os.listdir(cachedir):
if item.endswith(".zip"):
bankname=item.split(".")[0]
cached.append(bankname)
return sorted(cached)
class SVBank:
def __init__(self, name, zipfile):
self.name=name
self.zipfile=zipfile
@property
def wavfiles(self):
return [item.filename
for item in self.zipfile.infolist()]
class SVBanks(dict):
@classmethod
def initialise(self,
s3,
bucketname,
prefix="banks",
cachedir="tmp/banks"):
s3keys, cached = (list_s3_keys(s3, bucketname, prefix),
list_cached(cachedir))
banks={}
for s3key in s3keys:
bankname=s3key.split("/")[-1].split(".")[0]
cachefilename="%s/%s.zip" % (cachedir, bankname)
if bankname not in cached:
print ("INFO: fetching %s" % s3key)
buf=io.BytesIO(s3.get_object(Bucket=bucketname,
Key=s3key)["Body"].read())
with open(cachefilename, 'wb') as f:
f.write(buf.getvalue())
zf=zipfile.ZipFile(buf, "r")
else:
zf=zipfile.ZipFile(cachefilename)
bank=SVBank(name=bankname,
zipfile=zf)
banks[bankname]=bank
return SVBanks(banks)
def __init__(self, item={}):
dict.__init__(self, item)
def get_wavfile(self, sample):
return self[sample["bank"]].zipfile.open(sample["file"], 'r')
if __name__=="__main__":
pass
from banks import SVBanks
from export import export_wav
from model import SVPatch
from parse import parse_line
from project import SVProject
from datetime import datetime
import boto3, cmd, json, os, random, re, readline, yaml
Modules, Links, Machines, Terms, Env = [yaml.safe_load(open("%s.yaml" % attr).read())
for attr in "modules|links|machines|terms|env".split("|")]
Nouns, Adjectives = [yaml.safe_load(open("%s.yaml" % attr).read())
for attr in "nouns|adjectives".split("|")]
HistorySize=100
"""
- https://stackoverflow.com/questions/7331462/check-if-a-string-is-a-possible-abbrevation-for-a-name
"""
def is_abbrev(abbrev, text):
abbrev=abbrev.lower()
text=text.lower()
words=text.split()
if not abbrev:
return True
if abbrev and not text:
return False
if abbrev[0]!=text[0]:
return False
else:
return (is_abbrev(abbrev[1:],' '.join(words[1:])) or
any(is_abbrev(abbrev[1:],text[i+1:])
for i in range(len(words[0]))))
def random_filename(prefix):
ts=datetime.utcnow().strftime("%Y-%m-%d-%H-%M-%S")
return "%s-%s-%s-%s" % (ts,
prefix,
random.choice(Adjectives),
random.choice(Nouns))
def render_patches(prefix):
def decorator(fn):
def wrapped(self, *args, **kwargs):
self.filename=random_filename(prefix)
print ("INFO: %s" % self.filename)
self.patches=fn(self, *args, **kwargs)
self.dump_json()
self.dump_sunvox()
return wrapped
return decorator
def assert_project(fn):
def wrapped(self, *args, **kwargs):
if not self.patches:
raise RuntimeError("no patches found")
return fn(self, *args, **kwargs)
return wrapped
class SVEnvironment(dict):
def __init__(self, item={}):
dict.__init__(self, item)
def lookup(self, abbrev):
matches=[]
for key in self:
if is_abbrev(abbrev, key):
matches.append(key)
if matches==[]:
raise RuntimeError("%s not found" % abbrev)
elif len(matches) > 1:
raise RuntimeError("multiple key matches for %s" % abbrev)
return matches.pop()
class SVBaseCli(cmd.Cmd):
prompt=">>> "
def __init__(self,
s3,
bucketname,
env,
modules,
links,
historysize=HistorySize):
cmd.Cmd.__init__(self)
self.s3=s3
self.bucketname=bucketname
self.outdir="tmp"
self.init_subdirs()
self.modules=modules
self.links=links
self.env=SVEnvironment(env)
self.patches=None
self.filename=None
self.historyfile=os.path.expanduser("%s/.clihistory" % self.outdir)
self.historysize=historysize
def init_subdirs(self, subdirs=["json", "sunvox", "wav"]):
for subdir in subdirs:
path="%s/%s" % (self.outdir, subdir)
if not os.path.exists(path):
os.makedirs(path)
def preloop(self):
if os.path.exists(self.historyfile):
readline.read_history_file(self.historyfile)
def dump_json(self):
filename="%s/json/%s.json" % (self.outdir,
self.filename)
with open(filename, 'w') as f:
f.write(json.dumps(self.patches,
indent=2))
def render_project(self):
rendered=[patch.render(nticks=self.env["nticks"],
density=self.env["density"],
temperature=self.env["temperature"])
for patch in self.patches]
return SVProject().render(patches=rendered,
modules=self.modules,
links=self.links,
banks=self.banks,
bpm=self.env["bpm"])
def dump_sunvox(self):
filename="%s/sunvox/%s.sunvox" % (self.outdir,
self.filename)
with open(filename, 'wb') as f:
project=self.render_project()
project.write_to(f)
@parse_line()
def do_show_params(self):
for key in sorted(self.env.keys()):
print ("%s: %s" % (key, self.env[key]))
@parse_line(config=[{"name": "frag",
"type": "str"},
{"name": "value",
"type": "number"}])
def do_set_param(self, frag, value):
key=self.env.lookup(frag)
if key:
self.env[key]=value
print ("INFO: %s=%s" % (key, self.env[key]))
else:
print ("WARNING: %s not found" % frag)
@parse_line()
def do_list_projects(self):
for filename in sorted(os.listdir(self.outdir+"/json")):
print (filename.split(".")[0])
@parse_line(config=[{"name": "stem",
"type": "str"}])
def do_load_project(self, stem):
matches=[filename
for filename in sorted(os.listdir(self.outdir+"/json"))
if stem in filename]
if matches==[]:
print ("WARNING: no matches")
elif len(matches)==1:
self.filename=matches.pop().split(".")[0]
print ("INFO: %s" % self.filename)
abspath="%s/json/%s.json" % (self.outdir, self.filename)
patches=json.loads(open(abspath).read())
self.patches=[SVPatch(**patch)
for patch in patches]
else:
print ("WARNING: multiple matches")
@parse_line()
def do_clean_projects(self, subdirs=["json", "sunvox"]):
for subdir in subdirs:
os.system("rm -rf %s/%s" % (self.outdir, subdir))
self.init_subdirs()
@parse_line()
@assert_project
def do_export_wav(self):
filename="%s/wav/%s.wav" % (self.outdir, self.filename)
project=self.render_project()
with open(filename, 'wb') as f:
f.write(export_wav(project=project).getvalue())
def do_exit(self, _):
return self.do_quit(None)
def do_quit(self, _):
print ("INFO: exiting")
return True
def postloop(self):
readline.set_history_length(self.historysize)
readline.write_history_file(self.historyfile)
class SVBankCli(SVBaseCli):
def __init__(self,
banks,
pool,
mapping,
*args,
**kwargs):
SVBaseCli.__init__(self, *args, **kwargs)
self.banks=banks
self.pool=pool
self.mapping=mapping
@parse_line()
def do_show_tags(self):
print (yaml.safe_dump(self.pool.tags,
default_flow_style=False))
@parse_line()
def do_show_mapping(self):
for key in sorted(self.mapping.keys()):
print ("%s: %s" % (key, self.mapping[key]))
@parse_line()
def do_randomise_mapping(self):
tags=list(self.pool.tags.keys())
for key in sorted(self.mapping.keys()):
self.mapping[key]=random.choice(tags)
print ("%s: %s" % (key, self.mapping[key]))
@parse_line(config=[{"name": "key",
"type": "str"},
{"name": "value",
"type": "str"}])
def do_set_mapping(self, key, value):
if key not in self.mapping:
raise RuntimeError("%s not found in mapping" % key)
tags=list(self.pool.tags.keys())
if value not in tags:
raise RuntimeError("%s not found in tags" % value)
self.mapping[key]=value
class SVCli(SVBankCli):
intro="Welcome to the Sunvox Euclid Beats CLI ;)"
def __init__(self,
machines,
*args,
**kwargs):
self.machines=machines
mapping={machine["tag"]: machine["default"]
for machine in machines
if "tag" in machine}
SVBankCli.__init__(self, mapping=mapping, *args, **kwargs)
@parse_line()
@render_patches(prefix="random")
def do_randomise_patches(self):
patches=[]
for i in range(self.env["npatches"]):
patch=SVPatch.randomise(machines=self.machines,
pool=self.pool,
mapping=self.mapping)
patches.append(patch)
return patches
@parse_line(config=[{"name": "i",
"type": "int"}])
@assert_project
@render_patches(prefix="mutation")
def do_mutate_patterns(self, i, attrs="level|volume|trig|pattern".split("|")):
root=self.patches[i % len(self.patches)]
patches=[root]
for i in range(self.env["npatches"]-1):
patch=root.clone()
for machine in patch["machines"]:
for attr in attrs:
if attr in machine["seeds"]:
machine["seeds"][attr]=int(1e8*random.random())
patches.append(patch)
return patches
@parse_line(config=[{"name": "i",
"type": "int"}])
@assert_project
@render_patches(prefix="mutation")
def do_mutate_samples(self, i, attrs="level|volume|trig|pattern|sample".split("|")):
root=self.patches[i % len(self.patches)]
patches=[root]
for i in range(self.env["npatches"]-1):
patch=root.clone()
for machine in patch["machines"]:
for attr in attrs:
if attr in machine["seeds"]:
machine["seeds"][attr]=int(1e8*random.random())
patches.append(patch)
return patches
class SVPool(list):
def __init__(self, items=[]):
list.__init__(self, items)
@property
def tags(self):
tags={}
for sample in self:
if "tags" in sample:
for tag in sample["tags"]:
tags.setdefault(tag, 0)
tags[tag]+=1
return tags
def filter_by_tag(self, tag):
return [sample for sample in self
if "tags" in sample and tag in sample["tags"]]
def init_pool(banks):
def tagify(filename, terms=Terms):
tags = []
for tag, term in terms.items():
if re.search(term, filename, re.I):
tags.append(tag)
return tags
pool, untagged = SVPool(), []
for bankname, bank in banks.items():
for wavfile in bank.wavfiles:
tags=tagify(wavfile)
sample={"bank": bank.name,
"file": wavfile,
"tags": tags}
if tags!=[]:
pool.append(sample)
else:
untagged.append(sample)
return pool, untagged
if __name__=="__main__":
try:
bucketname=os.environ["ASSETS_BUCKET"]
if bucketname in ["", None]:
raise RuntimeError("ASSETS_BUCKET does not exist")
s3=boto3.client("s3")
banks=SVBanks.initialise(s3, bucketname)
pool, untagged = init_pool(banks)
SVCli(s3=s3,
machines=Machines,
bucketname=bucketname,
env=Env,
modules=Modules,
links=Links,
banks=banks,
pool=pool).cmdloop()
except RuntimeError as error:
print ("ERROR: %s" % str(error))
import importlib, random
def random_seed():
return int(1e8*random.random())
def Q(seed):
q=random.Random()
q.seed(seed)
return q
def load_class(path):
tokens=path.split(".")
modpath, classname = ".".join(tokens[:-1]), tokens[-1]
module=importlib.import_module(modpath)
return getattr(module, classname)
if __name__=="__main__":
pass
nticks: 16
npatches: 16
density: 0.75
temperature: 0.5
bpm: 120
tpb: 4 # ticks per beat
"""
- rv/tools/export.py
"""
import numpy as np
# from scipy.io import wavfile
import wavfile
# from sunvox import Slot
from sunvox.slot import Slot as RVSlot
from sunvox.buffered import BufferedProcess as RVBufferedProcess
from sunvox.buffered import float32, int16
from io import BytesIO
"""
- M8 requires 16 bit wav files
"""
def export_wav(project,
data_type=int16, # int16, float32
channels=2, # 1, 2
freq=44100): # 44100, 48000
p=RVBufferedProcess(freq=freq,
size=freq,
channels=channels,
data_type=data_type)
slot=RVSlot(project, process=p)
length=slot.get_song_length_frames()
output=np.zeros((length, 2), data_type)
position=0
slot.play_from_beginning()
while position < length:
buffer=p.fill_buffer()
end_pos=min(position+freq, length)
copy_size=end_pos-position
output[position:end_pos]=buffer[:copy_size]
position=end_pos
buf=BytesIO()
wavfile.write(buf, freq, output)
p.deinit()
p.kill()
buf.seek(0)
return buf
if __name__ == "__main__":
pass
- class: sequencers.EuclidSequencer
name: LoSampler
tag: lo
default: clap
params:
density: 0.33333
modulation:
sample:
step: 4
threshold: 0.5
pattern:
step: 4
threshold: 0.5
nsamples: 4
- class: sequencers.EuclidSequencer
name: MidSampler
tag: mid
default: kick
params:
density: 0.66666
modulation:
sample:
step: 4
threshold: 0.5
pattern:
step: 4
threshold: 0.5
nsamples: 4
- class: sequencers.EuclidSequencer
name: HiSampler
tag: hi
default: hat
params:
density: 0.9
modulation:
sample:
step: 4
threshold: 0.5
pattern:
step: 4
threshold: 0.5
nsamples: 4
- class: modulators.SampleHoldModulator
name: Echo/wet
params:
increment: 0.25
range:
- 0
- 1
step: 4
- class: modulators.SampleHoldModulator
name: Echo/feedback
params:
increment: 0.25
range:
- 0
- 1
step: 4
from core import load_class
class SVNoteTrig:
Volume=128
def __init__(self, mod, i,
sample=None,
note=None,
vel=1):
self.mod=mod
self.i=i
self.sample=sample
self.note=note
self.vel=vel
@property
def key(self):
return self.mod
def render(self,
modules,
*args):
if self.mod not in modules:
raise RuntimeError("mod %s not found" % self.mod)
mod=modules[self.mod]
modid=1+mod.index # NB 1+
note=1+(mod.lookup(self.sample) if self.sample else self.note)
vel=max(1, int(self.vel*self.Volume))
from rv.note import Note
return Note(module=modid,
note=note,
vel=vel)
class SVFXTrig:
CtrlMult=256
def __init__(self, target, value, i):
self.target=target
self.value=value
self.i=i
@property
def mod(self):
return self.target.split("/")[0]
@property
def ctrl(self):
return self.target.split("/")[1]
@property
def key(self):
return self.target
def render(self,
modules,
controllers):
if (self.mod not in modules or
self.mod not in controllers):
raise RuntimeError("mod %s not found" % self.mod)
mod, controller = modules[self.mod], controllers[self.mod]
modid=1+mod.index # NB 1+
if self.ctrl not in controller:
raise RuntimeError("ctrl %s not found in mod %s" % (self.ctrl,
self.mod))
ctrlid=self.CtrlMult*controller[self.ctrl]
from rv.note import Note
return Note(module=modid,
ctl=ctrlid,
val=self.value)
class SVTracks(dict):
def __init__(self, nticks, item={}):
dict.__init__(self)
self.nticks=nticks
class SVMachines(list):
@classmethod
def randomise(self,
machines,
**kwargs):
return SVMachines([load_class(machine["class"]).randomise(machine=machine,
**kwargs)
for machine in machines])
def __init__(self, machines):
list.__init__(self, [load_class(machine["class"])(machine=machine)
for machine in machines])
def clone(self):
return SVMachines([machine.clone()
for machine in self])
class SVPatch(dict):
@classmethod
def randomise(self, machines, **kwargs):
return SVPatch(machines=SVMachines.randomise(machines=machines,
**kwargs))
def __init__(self,
machines):
dict.__init__(self, {"machines": SVMachines(machines)})
def clone(self):
return SVPatch(machines=self["machines"].clone())
def render(self,
nticks,
density,
temperature):
tracks=SVTracks(nticks=nticks)
for machine in self["machines"]:
for trig in machine.render(nticks=nticks,
density=density,
temperature=temperature):
tracks.setdefault(trig.key, [])
tracks[trig.key].append(trig)
return tracks
if __name__=="__main__":
pass
from core import Q, random_seed
from model import SVFXTrig
import copy
class SampleHoldModulator(dict):
@classmethod
def randomise(self,
machine,
**kwargs):
return SampleHoldModulator({"name": machine["name"],
"class": machine["class"],
"params": machine["params"],
"seeds": {"level": random_seed()}})
def __init__(self, machine):
dict.__init__(self, machine)
for k, v in machine["params"].items():
setattr(self, k, v)
def clone(self):
return SampleHoldModulator({"name": self["name"],
"class": self["class"],
"params": copy.deepcopy(self["params"]),
"seeds": dict(self["seeds"])})
def render(self, nticks, minvalue='0000', maxvalue='8000', **kwargs):
minval, maxval = (int(minvalue, 16),
int(maxvalue, 16))
q=Q(self["seeds"]["level"])
for i in range(nticks):
v=self.sample_hold(q, i)
if v!=None: # explicit because could return zero
value=(v*maxval-minval)+minval
yield SVFXTrig(target=self["name"],
value=value,
i=i)
def sample_hold(self, q, i):
if 0 == i % self.step:
floor, ceil = self.range
v=floor+(ceil-floor)*q.random()
return self.increment*int(0.5+v/self.increment)
if __name__=="__main__":
pass
- name: MidSampler
class: sampler.SVSampler
- name: LoSampler
class: sampler.SVSampler
- name: HiSampler
class: sampler.SVSampler
- name: Echo
class: rv.modules.echo.Echo
defaults:
dry: 256
wet: 256
delay: 36
delay_unit: 3 # tick

ideas 04/05/23

  • sunvox 303

  • mikey 303

  • freeze and echo wash

  • vordhosbn / shaker

  • native percussion

  • breakbeats

  • vocals and vocoding

  • city dreams sounds

  • chords and sweeps

  • tidal syntax

  • livecoding/dll

  • breakbeats

  • granular

  • stabs

  • drones

- ability
- abroad
- abuse
- access
- accident
- account
- act
- action
- active
- activity
- actor
- addition
- address
- administration
- adult
- advance
- advantage
- advertising
- advice
- affair
- affect
- afternoon
- age
- agency
- agent
- agreement
- air
- airline
- airport
- alarm
- alcohol
- alternative
- ambition
- amount
- analysis
- analyst
- anger
- angle
- animal
- annual
- answer
- anxiety
- anybody
- anything
- anywhere
- apartment
- appeal
- appearance
- apple
- application
- appointment
- area
- argument
- arm
- army
- arrival
- art
- article
- aside
- ask
- aspect
- assignment
- assist
- assistance
- assistant
- associate
- association
- assumption
- atmosphere
- attack
- attempt
- attention
- attitude
- audience
- author
- average
- award
- awareness
- baby
- back
- background
- bad
- bag
- bake
- balance
- ball
- band
- bank
- bar
- base
- baseball
- basis
- basket
- bat
- bath
- bathroom
- battle
- beach
- bear
- beat
- beautiful
- bed
- bedroom
- beer
- beginning
- being
- bell
- belt
- bench
- bend
- benefit
- bet
- beyond
- bicycle
- bid
- big
- bike
- bill
- bird
- birth
- birthday
- bit
- bite
- bitter
- black
- blame
- blank
- blind
- block
- blood
- blow
- blue
- board
- boat
- body
- bone
- bonus
- book
- boot
- border
- boss
- bother
- bottle
- bottom
- bowl
- box
- boy
- boyfriend
- brain
- branch
- brave
- bread
- break
- breakfast
- breast
- breath
- brick
- bridge
- brief
- brilliant
- broad
- brother
- brown
- brush
- buddy
- budget
- bug
- building
- bunch
- burn
- bus
- business
- button
- buy
- buyer
- cabinet
- cable
- cake
- calendar
- call
- calm
- camera
- camp
- campaign
- can
- cancel
- cancer
- candidate
- candle
- candy
- cap
- capital
- car
- card
- care
- career
- carpet
- carry
- case
- cash
- cat
- catch
- category
- cause
- celebration
- cell
- chain
- chair
- challenge
- champion
- championship
- chance
- change
- channel
- chapter
- character
- charge
- charity
- chart
- check
- cheek
- chemical
- chemistry
- chest
- chicken
- child
- childhood
- chip
- chocolate
- choice
- church
- cigarette
- city
- claim
- class
- classic
- classroom
- clerk
- click
- client
- climate
- clock
- closet
- clothes
- cloud
- club
- clue
- coach
- coast
- coat
- code
- coffee
- cold
- collar
- collection
- college
- combination
- combine
- comfort
- comfortable
- command
- comment
- commercial
- commission
- committee
- common
- communication
- community
- company
- comparison
- competition
- complaint
- complex
- computer
- concentrate
- concept
- concern
- concert
- conclusion
- condition
- conference
- confidence
- conflict
- confusion
- connection
- consequence
- consideration
- consist
- constant
- construction
- contact
- contest
- context
- contract
- contribution
- control
- conversation
- convert
- cook
- cookie
- copy
- corner
- cost
- count
- counter
- country
- county
- couple
- courage
- course
- court
- cousin
- cover
- cow
- crack
- craft
- crash
- crazy
- cream
- creative
- credit
- crew
- criticism
- cross
- cry
- culture
- cup
- currency
- current
- curve
- customer
- cut
- cycle
- damage
- dance
- dare
- dark
- data
- database
- date
- daughter
- day
- dead
- deal
- dealer
- dear
- death
- debate
- debt
- decision
- deep
- definition
- degree
- delay
- delivery
- demand
- department
- departure
- dependent
- deposit
- depression
- depth
- description
- design
- designer
- desire
- desk
- detail
- development
- device
- devil
- diamond
- diet
- difference
- difficulty
- dig
- dimension
- dinner
- direction
- director
- dirt
- disaster
- discipline
- discount
- discussion
- disease
- dish
- disk
- display
- distance
- distribution
- district
- divide
- doctor
- document
- dog
- door
- dot
- double
- doubt
- draft
- drag
- drama
- draw
- drawer
- drawing
- dream
- dress
- drink
- drive
- driver
- drop
- drunk
- due
- dump
- dust
- duty
- ear
- earth
- ease
- east
- eat
- economics
- economy
- edge
- editor
- education
- effect
- effective
- efficiency
- effort
- egg
- election
- elevator
- emergency
- emotion
- emphasis
- employ
- employee
- employer
- employment
- end
- energy
- engine
- engineer
- engineering
- entertainment
- enthusiasm
- entrance
- entry
- environment
- equal
- equipment
- equivalent
- error
- escape
- essay
- establishment
- estate
- estimate
- evening
- event
- evidence
- exam
- examination
- example
- exchange
- excitement
- excuse
- exercise
- exit
- experience
- expert
- explanation
- expression
- extension
- extent
- external
- extreme
- eye
- face
- fact
- factor
- fail
- failure
- fall
- familiar
- family
- fan
- farm
- farmer
- fat
- father
- fault
- fear
- feature
- fee
- feed
- feedback
- feel
- feeling
- female
- few
- field
- fight
- figure
- file
- fill
- film
- final
- finance
- finding
- finger
- finish
- fire
- fish
- fishing
- fix
- flight
- floor
- flow
- flower
- fly
- focus
- fold
- following
- food
- foot
- football
- force
- forever
- form
- formal
- fortune
- foundation
- frame
- freedom
- friend
- friendship
- front
- fruit
- fuel
- fun
- function
- funeral
- funny
- future
- gain
- game
- gap
- garage
- garbage
- garden
- gas
- gate
- gather
- gear
- gene
- general
- gift
- girl
- girlfriend
- give
- glad
- glass
- glove
- goal
- god
- gold
- golf
- good
- government
- grab
- grade
- grand
- grandfather
- grandmother
- grass
- great
- green
- grocery
- ground
- group
- growth
- guarantee
- guard
- guess
- guest
- guidance
- guide
- guitar
- guy
- habit
- hair
- half
- hall
- hand
- handle
- hang
- harm
- hat
- hate
- head
- health
- hearing
- heart
- heat
- heavy
- height
- hell
- hello
- help
- hide
- high
- highlight
- highway
- hire
- historian
- history
- hit
- hold
- hole
- holiday
- home
- homework
- honey
- hook
- hope
- horror
- horse
- hospital
- host
- hotel
- hour
- house
- housing
- human
- hunt
- hurry
- hurt
- husband
- ice
- idea
- ideal
- illegal
- image
- imagination
- impact
- implement
- importance
- impress
- impression
- improvement
- incident
- income
- increase
- independence
- independent
- indication
- individual
- industry
- inevitable
- inflation
- influence
- information
- initial
- initiative
- injury
- insect
- inside
- inspection
- inspector
- instance
- instruction
- insurance
- intention
- interaction
- interest
- internal
- international
- internet
- interview
- introduction
- investment
- invite
- iron
- island
- issue
- item
- jacket
- job
- join
- joint
- joke
- judge
- judgment
- juice
- jump
- junior
- jury
- keep
- key
- kick
- kid
- kill
- kind
- king
- kiss
- kitchen
- knee
- knife
- knowledge
- lab
- lack
- ladder
- lady
- lake
- land
- landscape
- language
- laugh
- law
- lawyer
- lay
- layer
- lead
- leader
- leadership
- leading
- league
- leather
- leave
- lecture
- leg
- length
- lesson
- let
- letter
- level
- library
- lie
- life
- lift
- light
- limit
- line
- link
- lip
- list
- listen
- literature
- living
- load
- loan
- local
- location
- lock
- log
- long
- look
- loss
- love
- low
- luck
- lunch
- machine
- magazine
- mail
- main
- maintenance
- major
- make
- male
- mall
- man
- management
- manager
- manner
- manufacturer
- many
- map
- march
- mark
- market
- marketing
- marriage
- master
- match
- mate
- material
- math
- matter
- maximum
- maybe
- meal
- meaning
- measurement
- meat
- media
- medicine
- medium
- meet
- meeting
- member
- membership
- memory
- mention
- menu
- mess
- message
- metal
- method
- middle
- midnight
- might
- milk
- mind
- mine
- minimum
- minor
- minute
- mirror
- miss
- mission
- mistake
- mix
- mixture
- mobile
- mode
- model
- mom
- moment
- money
- monitor
- month
- mood
- morning
- mortgage
- most
- mother
- motor
- mountain
- mouse
- mouth
- move
- movie
- mud
- muscle
- music
- nail
- name
- nasty
- nation
- national
- native
- natural
- nature
- neat
- necessary
- neck
- negative
- negotiation
- nerve
- net
- network
- news
- newspaper
- night
- nobody
- noise
- normal
- north
- nose
- note
- nothing
- notice
- novel
- number
- nurse
- object
- objective
- obligation
- occasion
- offer
- office
- officer
- official
- oil
- opening
- operation
- opinion
- opportunity
- opposite
- option
- orange
- order
- ordinary
- organization
- original
- other
- outcome
- outside
- oven
- owner
- pace
- pack
- package
- page
- pain
- paint
- painting
- pair
- panic
- paper
- parent
- park
- parking
- part
- particular
- partner
- party
- pass
- passage
- passenger
- passion
- past
- path
- patience
- patient
- pattern
- pause
- pay
- payment
- peace
- peak
- pen
- penalty
- pension
- people
- percentage
- perception
- performance
- period
- permission
- permit
- person
- personal
- personality
- perspective
- phase
- philosophy
- phone
- photo
- phrase
- physical
- physics
- piano
- pick
- picture
- pie
- piece
- pin
- pipe
- pitch
- pizza
- place
- plan
- plane
- plant
- plastic
- plate
- platform
- play
- player
- pleasure
- plenty
- poem
- poet
- poetry
- point
- police
- policy
- politics
- pollution
- pool
- pop
- population
- position
- positive
- possession
- possibility
- possible
- post
- pot
- potato
- potential
- pound
- power
- practice
- preference
- preparation
- presence
- present
- presentation
- president
- press
- pressure
- price
- pride
- priest
- primary
- principle
- print
- prior
- priority
- private
- prize
- problem
- procedure
- process
- produce
- product
- profession
- professional
- professor
- profile
- profit
- program
- progress
- project
- promise
- promotion
- prompt
- proof
- property
- proposal
- protection
- psychology
- public
- pull
- punch
- purchase
- purple
- purpose
- push
- put
- quality
- quantity
- quarter
- queen
- question
- quiet
- quit
- quote
- race
- radio
- rain
- raise
- range
- rate
- ratio
- raw
- reach
- reaction
- read
- reading
- reality
- reason
- reception
- recipe
- recognition
- recommendation
- record
- recording
- recover
- red
- reference
- reflection
- refrigerator
- refuse
- region
- register
- regret
- regular
- relation
- relationship
- relative
- release
- relief
- remote
- remove
- rent
- repair
- repeat
- replacement
- reply
- report
- representative
- republic
- reputation
- request
- requirement
- research
- reserve
- resident
- resist
- resolution
- resolve
- resort
- resource
- respect
- respond
- response
- responsibility
- rest
- restaurant
- result
- return
- reveal
- revenue
- review
- revolution
- reward
- rice
- rich
- ride
- ring
- rip
- rise
- risk
- river
- road
- rock
- role
- roll
- roof
- room
- rope
- rough
- round
- routine
- row
- royal
- rub
- ruin
- rule
- run
- rush
- sad
- safe
- safety
- sail
- salad
- salary
- sale
- salt
- sample
- sand
- sandwich
- satisfaction
- save
- savings
- scale
- scene
- schedule
- scheme
- school
- science
- score
- scratch
- screen
- screw
- script
- sea
- search
- season
- seat
- second
- secret
- secretary
- section
- sector
- security
- selection
- self
- sell
- senior
- sense
- sensitive
- sentence
- series
- serve
- service
- session
- set
- setting
- sex
- shake
- shame
- shape
- share
- she
- shelter
- shift
- shine
- ship
- shirt
- shock
- shoe
- shoot
- shop
- shopping
- shot
- shoulder
- show
- shower
- sick
- side
- sign
- signal
- signature
- significance
- silly
- silver
- simple
- sing
- singer
- single
- sink
- sir
- sister
- site
- situation
- size
- skill
- skin
- skirt
- sky
- sleep
- slice
- slide
- slip
- smell
- smile
- smoke
- snow
- society
- sock
- soft
- software
- soil
- solid
- solution
- somewhere
- son
- song
- sort
- sound
- soup
- source
- south
- space
- spare
- speaker
- special
- specialist
- specific
- speech
- speed
- spell
- spend
- spirit
- spiritual
- spite
- split
- sport
- spot
- spray
- spread
- spring
- square
- stable
- staff
- stage
- stand
- standard
- star
- start
- state
- statement
- station
- status
- stay
- steak
- steal
- step
- stick
- still
- stock
- stomach
- stop
- storage
- store
- storm
- story
- strain
- stranger
- strategy
- street
- strength
- stress
- stretch
- strike
- string
- strip
- stroke
- structure
- struggle
- student
- studio
- study
- stuff
- stupid
- style
- subject
- substance
- success
- suck
- sugar
- suggestion
- suit
- summer
- sun
- supermarket
- support
- surgery
- surprise
- surround
- survey
- suspect
- sweet
- swim
- swimming
- swing
- switch
- sympathy
- system
- table
- tackle
- tale
- talk
- tank
- tap
- target
- task
- taste
- tax
- tea
- teach
- teacher
- teaching
- team
- tear
- technology
- telephone
- television
- tell
- temperature
- temporary
- tennis
- tension
- term
- test
- text
- thanks
- theme
- theory
- thing
- thought
- throat
- ticket
- tie
- till
- time
- tip
- title
- today
- toe
- tomorrow
- tone
- tongue
- tonight
- tool
- tooth
- top
- topic
- total
- touch
- tough
- tour
- tourist
- towel
- tower
- town
- track
- trade
- tradition
- traffic
- train
- trainer
- training
- transition
- transportation
- trash
- travel
- treat
- tree
- trick
- trip
- trouble
- truck
- trust
- truth
- try
- tune
- turn
- twist
- type
- uncle
- understanding
- union
- unique
- unit
- university
- upper
- upstairs
- use
- user
- usual
- vacation
- valuable
- value
- variation
- variety
- vast
- vegetable
- vehicle
- version
- video
- view
- village
- virus
- visit
- visual
- voice
- volume
- wait
- wake
- walk
- wall
- war
- warning
- wash
- watch
- water
- wave
- way
- weakness
- wealth
- wear
- weather
- web
- wedding
- week
- weekend
- weight
- weird
- welcome
- west
- western
- wheel
- whereas
- while
- white
- whole
- wife
- will
- win
- wind
- window
- wine
- wing
- winner
- winter
- wish
- witness
- woman
- wonder
- wood
- word
- work
- worker
- working
- world
- worry
- worth
- wrap
- writer
- writing
- yard
- year
- yellow
- yesterday
- you
- young
- youth
- zone
import re, traceback
def matches_number(value):
return re.search("^\\-?\\d+(\\.\\d+)?$", value)!=None
def matches_int(value):
return re.search("^\\-?\\d+$", value)!=None
def matches_str(value):
return True
def parse_number(value):
return int(value) if matches_int(value) else float(value)
def parse_int(value):
return int(value)
def parse_str(value):
return value
def parse_line(config=[]):
def decorator(fn):
def wrapped(self, line):
try:
args=[tok for tok in line.split(" ") if tok!='']
if len(args) < len(config):
raise RuntimeError("please enter %s" % ", ".join([item["name"]
for item in config]))
kwargs={}
for item, argval in zip(config, args[:len(config)]):
matcherfn=eval("matches_%s" % item["type"])
matcherargs=[argval]
if not matcherfn(*matcherargs):
raise RuntimeError("%s value is invalid" % item["name"])
parserfn=eval("parse_%s" % item["type"])
kwargs[item["name"]]=parserfn(argval)
return fn(self, **kwargs)
except RuntimeError as error:
print ("ERROR: %s" % str(error))
except Exception as error:
print ("EXCEPTION: %s" % ''.join(traceback.TracebackException.from_exception(error).format()))
return wrapped
return decorator
if __name__=="__main__":
pass
from rv.api import Project as RVProject
from rv.pattern import Pattern as RVPattern
from rv.note import Note as RVNote
from core import load_class
from sampler import SVSamplerPool
import random
Volume, Height = 256, 64
class SVColor(list):
@classmethod
def randomise(self,
offset=64,
contrast=128,
n=16):
def randomise(offset):
return [int(offset+random.random()*(255-offset))
for i in range(3)]
for i in range(n):
color=randomise(offset)
if (max(color)-min(color)) > contrast:
return SVColor(color)
return SVColor([127 for i in range(3)])
def __init__(self, rgb=[]):
list.__init__(self, rgb)
def mutate(self,
contrast=32):
values=range(-contrast, contrast)
return SVColor([min(255, max(0, rgb+random.choice(values)))
for rgb in self])
class SVOffset:
def __init__(self):
self.value=0
self.count=0
def increment(self, value):
self.value+=value
self.count+=1
class SVProject:
def populate_sample_pool(self, patches, pool):
for patch in patches:
for track in patch.values():
for trig in track:
if (hasattr(trig, "sample") and trig.sample):
pool.add(trig.sample)
def init_module_classes(fn):
def wrapped(self,
proj,
patches,
modules,
links,
banks):
for mod in modules:
modclass=load_class(mod["class"])
kwargs={}
if mod["class"].lower().endswith("sampler"):
pool=SVSamplerPool()
self.populate_sample_pool(patches=patches,
pool=pool)
kwargs={"banks": banks,
"pool": pool}
mod["instance"]=modclass(**kwargs)
return fn(self, proj, patches, modules, links, banks)
return wrapped
@init_module_classes
def init_modules(self,
proj,
patches,
modules,
links,
banks):
modules_={}
for i, moditem in enumerate(modules):
mod, name = moditem["instance"], moditem["name"]
setattr(mod, "name", name)
if "defaults" in moditem:
for k, v in moditem["defaults"].items():
mod.set_raw(k, v)
proj.attach_module(mod)
modules_[name]=mod
output=sorted(proj.modules, key=lambda x: -x.index).pop()
for src, dest in links:
proj.connect(modules_[src],
output if dest=="Output" else modules_[dest])
return modules_
def attach_pattern(fn):
def wrapped(*args, **kwargs):
rvpat=fn(*args, **kwargs)
kwargs["patterns"].append(rvpat)
kwargs["offset"].increment(kwargs["patch"].nticks)
return wrapped
@attach_pattern
def init_pattern(self,
patterns,
modules,
controllers,
patch,
offset,
color,
height=Height):
trigs=[{note.i:note
for note in track}
for key, track in patch.items()]
def notefn(self, j, i):
return trigs[i][j].render(modules,
controllers) if j in trigs[i] else RVNote()
return RVPattern(lines=patch.nticks,
tracks=len(patch),
x=offset.value,
y_size=height,
bg_color=color).set_via_fn(notefn)
def init_controllers(self, modules):
controllers={}
for mod in modules.values():
controllers.setdefault(mod.name, {})
for controller in mod.controllers.values():
controllers[mod.name].setdefault(controller.name, {})
controllers[mod.name][controller.name]=controller.number
return controllers
def init_patterns(self,
modules,
patches):
controllers=self.init_controllers(modules)
offset=SVOffset()
patterns, color = [], None
for i, patch in enumerate(patches):
color=SVColor.randomise() if 0==i%4 else color.mutate()
self.init_pattern(patterns=patterns,
modules=modules,
controllers=controllers,
patch=patch,
offset=offset,
color=color)
return patterns
def render(self,
patches,
modules,
links,
bpm,
banks=None,
volume=Volume):
proj=RVProject()
proj.initial_bpm=bpm
proj.global_volume=volume
modules_=self.init_modules(proj=proj,
patches=patches,
modules=modules,
links=links,
banks=banks)
proj.patterns=self.init_patterns(modules=modules_,
patches=patches)
return proj
if __name__=="__main__":
pass
awscli
boto3
botocore
numpy
pyyaml
git+https://github.com//metrasynth/radiant-voices
sunvox-dll-python
from rv.modules.sampler import Sampler as RVSampler
from rv.note import NOTE as RVNOTE
# from scipy.io import wavfile
import wavfile
import io, warnings
warnings.simplefilter("ignore", wavfile.WavFileWarning)
MaxSlots=120
"""
Sampler needs dedicated pool because can't afford to have duplicate samples, given limited number of slots
And duplicate slots can arise because two independently generated patches could utilise the same sample
Keys are used to provide an easy sample lookup mechanism
"""
class SVSamplerPool(list):
def __init__(self, items=[]):
list.__init__(self, items)
self.keys=[]
def add(self, sample):
key="%s/%s" % (sample["bank"],
sample["file"])
if key not in self.keys:
self.append(sample)
self.keys.append(key)
class SVSampler(RVSampler):
def __init__(self, banks, pool, maxslots=MaxSlots, *args, **kwargs):
RVSampler.__init__(self, *args, **kwargs)
if len(pool) > maxslots:
raise RuntimeError("SVBankSampler max slots exceeded")
self.pool=pool
notes=list(RVNOTE)
root=notes.index(RVNOTE.C5)
for i, sample in enumerate(self.pool):
self.note_samples[notes[i]]=i
src=banks.get_wavfile(sample)
self.load_sample(src, i)
svsample=self.samples[i]
svsample.relative_note+=(root-i)
"""
- https://github.com/metrasynth/gallery/blob/master/wicked.mmckpy#L497-L526
"""
def load_sample(self, src, slot, **kwargs):
sample = self.Sample()
freq, snd = wavfile.read(src)
if snd.dtype.name == 'int16':
sample.format = self.Format.int16
elif snd.dtype.name == 'float32':
sample.format = self.Format.float32
else:
raise RuntimeError("dtype %s Not supported" % snd.dtype.name)
if len(snd.shape) == 1:
size, = snd.shape
channels = 1
else:
size, channels = snd.shape
sample.rate = freq
sample.channels = {
1: RVSampler.Channels.mono,
2: RVSampler.Channels.stereo,
}[channels]
sample.data = snd.data.tobytes()
for key, value in kwargs.items():
setattr(sample, key, value)
self.samples[slot] = sample
return sample
def lookup(self, sample):
key="%s/%s" % (sample["bank"],
sample["file"])
return self.pool.keys.index(key)
if __name__=="__main__":
pass
from core import Q, random_seed
from model import SVNoteTrig, SVFXTrig
import copy, random, yaml
"""
https://club.tidalcycles.org/t/week-1-lesson-5-mini-notation-part-3/449
"""
"""
The Euclidean Algorithm Generates Traditional Musical Rhythms by Toussaint
(2,5) : A thirteenth century Persian rhythm called Khafif-e-ramal.
(3,4) : The archetypal pattern of the Cumbia from Colombia, as well as a Calypso rhythm from Trinidad.
(3,5,2) : Another thirteenth century Persian rhythm by the name of Khafif-e-ramal, as well as a Rumanian folk-dance rhythm.
(3,7) : A Ruchenitza rhythm used in a Bulgarian folk-dance.
(3,8) : The Cuban tresillo pattern.
(4,7) : Another Ruchenitza Bulgarian folk-dance rhythm.
(4,9) : The Aksak rhythm of Turkey.
(4,11) : The metric pattern used by Frank Zappa in his piece titled Outside Now.
(5,6) : Yields the York-Samai pattern, a popular Arab rhythm.
(5,7) : The Nawakhat pattern, another popular Arab rhythm.
(5,8) : The Cuban cinquillo pattern.
(5,9) : A popular Arab rhythm called Agsag-Samai.
(5,11) : The metric pattern used by Moussorgsky in Pictures at an Exhibition.
(5,12) : The Venda clapping pattern of a South African children’s song.
(5,16) : The Bossa-Nova rhythm necklace of Brazil.
(7,8) : A typical rhythm played on the Bendir (frame drum).
(7,12) : A common West African bell pattern.
(7,16,14) : A Samba rhythm necklace from Brazil.
(9,16) : A rhythm necklace used in the Central African Republic.
(11,24,14) : A rhythm necklace of the Aka Pygmies of Central Africa.
(13,24,5) : Another rhythm necklace of the Aka Pygmies of the upper Sangha
"""
Patterns=yaml.safe_load("""
- [2, 5]
- [3, 4]
- [3, 5, 2]
- [3, 7]
- [3, 8]
- [4, 7]
- [4, 9]
- [4, 11]
- [5, 6]
- [5, 7]
- [5, 8]
- [5, 9]
- [5, 11]
- [5, 12]
- [5, 16]
- [7, 8]
- [7, 12]
- [7, 16, 14]
- [9, 16]
- [11, 24, 14]
- [13, 24, 5]
""")
"""
https://raw.githubusercontent.com/brianhouse/bjorklund/master/__init__.py
"""
def bjorklund(steps, pulses):
steps = int(steps)
pulses = int(pulses)
if pulses > steps:
raise ValueError
pattern = []
counts = []
remainders = []
divisor = steps - pulses
remainders.append(pulses)
level = 0
while True:
counts.append(divisor // remainders[level])
remainders.append(divisor % remainders[level])
divisor = remainders[level]
level = level + 1
if remainders[level] <= 1:
break
counts.append(divisor)
def build(level):
if level == -1:
pattern.append(0)
elif level == -2:
pattern.append(1)
else:
for i in range(0, counts[level]):
build(level - 1)
if remainders[level] != 0:
build(level - 2)
build(level)
i = pattern.index(1)
pattern = pattern[i:] + pattern[0:i]
return pattern
class EuclidSequencer(dict):
@classmethod
def randomise(self,
machine,
pool,
mapping):
samples=pool.filter_by_tag(tag=mapping[machine["tag"]])
return EuclidSequencer({"name": machine["name"],
"class": machine["class"],
"params": machine["params"],
"samples": [random.choice(samples)
for i in range(machine["params"]["nsamples"])],
"seeds": {k:random_seed()
for k in "sample|trig|pattern|volume".split("|")}})
def __init__(self, machine, patterns = Patterns):
dict.__init__(self, machine)
for k, v in machine["params"].items():
setattr(self, k, v)
self.patterns=patterns
def clone(self):
return EuclidSequencer({"name": self["name"],
"class": self["class"],
"params": copy.deepcopy(self["params"]),
"samples": copy.deepcopy(self["samples"]),
"seeds": dict(self["seeds"])})
def random_pattern(self, q):
pulses, steps = q["pattern"].choice(self.patterns)[:2] # because some of Tidal euclid rhythms have 3 parameters
return bjorklund(pulses=pulses,
steps=steps)
def switch_pattern(self, q, i, temperature):
return (0 == i % self.modulation["pattern"]["step"] and
q["pattern"].random() < self.modulation["pattern"]["threshold"]*temperature)
def random_sample(self, q):
return q["sample"].choice(self["samples"])
def switch_sample(self, q, i, temperature):
return (0 == i % self.modulation["sample"]["step"] and
q["sample"].random() < self.modulation["sample"]["threshold"]*temperature)
def groove(self, q, i, n=5, var=0.1, drift=0.1):
for j in range(n+1):
k=2**(n-j)
if 0 == i % k:
sigma=q.gauss(0, var)
return 1-max(0, min(1, j*drift+sigma))
"""
- for the moment it's either/or in terms of sample/pattern switching
"""
def render(self, nticks, density, temperature):
q={k:Q(v) for k, v in self["seeds"].items()}
sample, pattern = (self.random_sample(q),
self.random_pattern(q))
for i in range(nticks):
if self.switch_sample(q, i, temperature):
sample=self.random_sample(q)
elif self.switch_pattern(q, i, temperature):
pattern=self.random_pattern(q)
beat=bool(pattern[i % len(pattern)])
if q["trig"].random() < (self.density*density) and beat:
volume=self.groove(q["volume"], i)
yield SVNoteTrig(mod=self["name"],
sample=sample,
vel=volume,
i=i)
if __name__=="__main__":
pass
#!/usr/bin/env bash
export ASSETS_BUCKET=octavox-assets
export AWS_DEFAULT_OUTPUT=table
export AWS_PROFILE=woldeploy
export PYTHONPATH=.
kick: (kick)|(kik)|(kk)|(bd)
bass: (bass)
kick-bass: (kick)|(kik)|(kk)|(bd)|(bass)
snare: (snare)|(sn)|(sd)
clap: (clap)|(clp)|(cp)|(hc)
snare-clap: (snare)|(sn)|(sd)|(clap)|(clp)|(cp)|(hc)
hat: (oh)|( ch)|(open)|(closed)|(hh)|(hat)
perc: (perc)|(prc)|(rim)|(tom)|(cow)|(rs)
sync: (syn)|(blip)
all-perc: (oh)|( ch)|(open)|(closed)|(hh)|(hat)|(perc)|(prc)|(rim)|(tom)|(cow)|(rs)|(syn)|(blip)
arcade: (arc)
break: (break)|(brk)|(cut)
chord: (chord)
drone: (dron)
fm: (fm)
fx: (fx)
glitch: (devine)|(glitch)|(gltch)
noise: (nois)
pad: (pad)
stab: (chord)|(stab)|(piano)
sweep: (swp)|(sweep)

short

  • save patches with patches key

  • mutes/mixer

  • pico/perkons play modes

  • perkons groove modes

  • feedback lfo

thoughts

  • see if you can get rid of SVTracks?
    • problem is you need tracks.nticks in a number of different places
  • do you need clone?
    • almost certainly yes because of mutation

done

  • convert link modules to decorator
  • implement init_module_classes as a decorator
  • move filter_samples into project
  • unpack mutation methods
  • move mutator min/max config values into class
  • refactor core variable in cli as modules
  • refactor modconfig refs
  • test removing feedback
  • remove reverb
  • don't think you need both SVTrigs and SVTracks
  • rename dsl as json
  • replace str(sample)
  • migrate stuff in core
  • rename euclid as sequencers, sample_hold as modulators
  • remove beats subdir from tmp
  • remove FeedbackSampleHold
  • shorten machine names
  • check what needs random_seed and Q
  • rename OCTAVOX_ASSETS_BUCKET
  • cleanup octavox.xxx refs
"""
- NB local wavfile.py implementation culled from scipy, as scipy is huge and currently doesn't play well with new macs
"""
"""
Module to read / write wav files using NumPy arrays
Functions
---------
`read`: Return the sample rate (in samples/sec) and data from a WAV file.
`write`: Write a NumPy array as a WAV file.
"""
import io
import sys
import numpy
import struct
import warnings
from enum import IntEnum
__all__ = [
'WavFileWarning',
'read',
'write'
]
class WavFileWarning(UserWarning):
pass
class WAVE_FORMAT(IntEnum):
"""
WAVE form wFormatTag IDs
Complete list is in mmreg.h in Windows 10 SDK. ALAC and OPUS are the
newest additions, in v10.0.14393 2016-07
"""
UNKNOWN = 0x0000
PCM = 0x0001
ADPCM = 0x0002
IEEE_FLOAT = 0x0003
VSELP = 0x0004
IBM_CVSD = 0x0005
ALAW = 0x0006
MULAW = 0x0007
DTS = 0x0008
DRM = 0x0009
WMAVOICE9 = 0x000A
WMAVOICE10 = 0x000B
OKI_ADPCM = 0x0010
DVI_ADPCM = 0x0011
IMA_ADPCM = 0x0011 # Duplicate
MEDIASPACE_ADPCM = 0x0012
SIERRA_ADPCM = 0x0013
G723_ADPCM = 0x0014
DIGISTD = 0x0015
DIGIFIX = 0x0016
DIALOGIC_OKI_ADPCM = 0x0017
MEDIAVISION_ADPCM = 0x0018
CU_CODEC = 0x0019
HP_DYN_VOICE = 0x001A
YAMAHA_ADPCM = 0x0020
SONARC = 0x0021
DSPGROUP_TRUESPEECH = 0x0022
ECHOSC1 = 0x0023
AUDIOFILE_AF36 = 0x0024
APTX = 0x0025
AUDIOFILE_AF10 = 0x0026
PROSODY_1612 = 0x0027
LRC = 0x0028
DOLBY_AC2 = 0x0030
GSM610 = 0x0031
MSNAUDIO = 0x0032
ANTEX_ADPCME = 0x0033
CONTROL_RES_VQLPC = 0x0034
DIGIREAL = 0x0035
DIGIADPCM = 0x0036
CONTROL_RES_CR10 = 0x0037
NMS_VBXADPCM = 0x0038
CS_IMAADPCM = 0x0039
ECHOSC3 = 0x003A
ROCKWELL_ADPCM = 0x003B
ROCKWELL_DIGITALK = 0x003C
XEBEC = 0x003D
G721_ADPCM = 0x0040
G728_CELP = 0x0041
MSG723 = 0x0042
INTEL_G723_1 = 0x0043
INTEL_G729 = 0x0044
SHARP_G726 = 0x0045
MPEG = 0x0050
RT24 = 0x0052
PAC = 0x0053
MPEGLAYER3 = 0x0055
LUCENT_G723 = 0x0059
CIRRUS = 0x0060
ESPCM = 0x0061
VOXWARE = 0x0062
CANOPUS_ATRAC = 0x0063
G726_ADPCM = 0x0064
G722_ADPCM = 0x0065
DSAT = 0x0066
DSAT_DISPLAY = 0x0067
VOXWARE_BYTE_ALIGNED = 0x0069
VOXWARE_AC8 = 0x0070
VOXWARE_AC10 = 0x0071
VOXWARE_AC16 = 0x0072
VOXWARE_AC20 = 0x0073
VOXWARE_RT24 = 0x0074
VOXWARE_RT29 = 0x0075
VOXWARE_RT29HW = 0x0076
VOXWARE_VR12 = 0x0077
VOXWARE_VR18 = 0x0078
VOXWARE_TQ40 = 0x0079
VOXWARE_SC3 = 0x007A
VOXWARE_SC3_1 = 0x007B
SOFTSOUND = 0x0080
VOXWARE_TQ60 = 0x0081
MSRT24 = 0x0082
G729A = 0x0083
MVI_MVI2 = 0x0084
DF_G726 = 0x0085
DF_GSM610 = 0x0086
ISIAUDIO = 0x0088
ONLIVE = 0x0089
MULTITUDE_FT_SX20 = 0x008A
INFOCOM_ITS_G721_ADPCM = 0x008B
CONVEDIA_G729 = 0x008C
CONGRUENCY = 0x008D
SBC24 = 0x0091
DOLBY_AC3_SPDIF = 0x0092
MEDIASONIC_G723 = 0x0093
PROSODY_8KBPS = 0x0094
ZYXEL_ADPCM = 0x0097
PHILIPS_LPCBB = 0x0098
PACKED = 0x0099
MALDEN_PHONYTALK = 0x00A0
RACAL_RECORDER_GSM = 0x00A1
RACAL_RECORDER_G720_A = 0x00A2
RACAL_RECORDER_G723_1 = 0x00A3
RACAL_RECORDER_TETRA_ACELP = 0x00A4
NEC_AAC = 0x00B0
RAW_AAC1 = 0x00FF
RHETOREX_ADPCM = 0x0100
IRAT = 0x0101
VIVO_G723 = 0x0111
VIVO_SIREN = 0x0112
PHILIPS_CELP = 0x0120
PHILIPS_GRUNDIG = 0x0121
DIGITAL_G723 = 0x0123
SANYO_LD_ADPCM = 0x0125
SIPROLAB_ACEPLNET = 0x0130
SIPROLAB_ACELP4800 = 0x0131
SIPROLAB_ACELP8V3 = 0x0132
SIPROLAB_G729 = 0x0133
SIPROLAB_G729A = 0x0134
SIPROLAB_KELVIN = 0x0135
VOICEAGE_AMR = 0x0136
G726ADPCM = 0x0140
DICTAPHONE_CELP68 = 0x0141
DICTAPHONE_CELP54 = 0x0142
QUALCOMM_PUREVOICE = 0x0150
QUALCOMM_HALFRATE = 0x0151
TUBGSM = 0x0155
MSAUDIO1 = 0x0160
WMAUDIO2 = 0x0161
WMAUDIO3 = 0x0162
WMAUDIO_LOSSLESS = 0x0163
WMASPDIF = 0x0164
UNISYS_NAP_ADPCM = 0x0170
UNISYS_NAP_ULAW = 0x0171
UNISYS_NAP_ALAW = 0x0172
UNISYS_NAP_16K = 0x0173
SYCOM_ACM_SYC008 = 0x0174
SYCOM_ACM_SYC701_G726L = 0x0175
SYCOM_ACM_SYC701_CELP54 = 0x0176
SYCOM_ACM_SYC701_CELP68 = 0x0177
KNOWLEDGE_ADVENTURE_ADPCM = 0x0178
FRAUNHOFER_IIS_MPEG2_AAC = 0x0180
DTS_DS = 0x0190
CREATIVE_ADPCM = 0x0200
CREATIVE_FASTSPEECH8 = 0x0202
CREATIVE_FASTSPEECH10 = 0x0203
UHER_ADPCM = 0x0210
ULEAD_DV_AUDIO = 0x0215
ULEAD_DV_AUDIO_1 = 0x0216
QUARTERDECK = 0x0220
ILINK_VC = 0x0230
RAW_SPORT = 0x0240
ESST_AC3 = 0x0241
GENERIC_PASSTHRU = 0x0249
IPI_HSX = 0x0250
IPI_RPELP = 0x0251
CS2 = 0x0260
SONY_SCX = 0x0270
SONY_SCY = 0x0271
SONY_ATRAC3 = 0x0272
SONY_SPC = 0x0273
TELUM_AUDIO = 0x0280
TELUM_IA_AUDIO = 0x0281
NORCOM_VOICE_SYSTEMS_ADPCM = 0x0285
FM_TOWNS_SND = 0x0300
MICRONAS = 0x0350
MICRONAS_CELP833 = 0x0351
BTV_DIGITAL = 0x0400
INTEL_MUSIC_CODER = 0x0401
INDEO_AUDIO = 0x0402
QDESIGN_MUSIC = 0x0450
ON2_VP7_AUDIO = 0x0500
ON2_VP6_AUDIO = 0x0501
VME_VMPCM = 0x0680
TPC = 0x0681
LIGHTWAVE_LOSSLESS = 0x08AE
OLIGSM = 0x1000
OLIADPCM = 0x1001
OLICELP = 0x1002
OLISBC = 0x1003
OLIOPR = 0x1004
LH_CODEC = 0x1100
LH_CODEC_CELP = 0x1101
LH_CODEC_SBC8 = 0x1102
LH_CODEC_SBC12 = 0x1103
LH_CODEC_SBC16 = 0x1104
NORRIS = 0x1400
ISIAUDIO_2 = 0x1401
SOUNDSPACE_MUSICOMPRESS = 0x1500
MPEG_ADTS_AAC = 0x1600
MPEG_RAW_AAC = 0x1601
MPEG_LOAS = 0x1602
NOKIA_MPEG_ADTS_AAC = 0x1608
NOKIA_MPEG_RAW_AAC = 0x1609
VODAFONE_MPEG_ADTS_AAC = 0x160A
VODAFONE_MPEG_RAW_AAC = 0x160B
MPEG_HEAAC = 0x1610
VOXWARE_RT24_SPEECH = 0x181C
SONICFOUNDRY_LOSSLESS = 0x1971
INNINGS_TELECOM_ADPCM = 0x1979
LUCENT_SX8300P = 0x1C07
LUCENT_SX5363S = 0x1C0C
CUSEEME = 0x1F03
NTCSOFT_ALF2CM_ACM = 0x1FC4
DVM = 0x2000
DTS2 = 0x2001
MAKEAVIS = 0x3313
DIVIO_MPEG4_AAC = 0x4143
NOKIA_ADAPTIVE_MULTIRATE = 0x4201
DIVIO_G726 = 0x4243
LEAD_SPEECH = 0x434C
LEAD_VORBIS = 0x564C
WAVPACK_AUDIO = 0x5756
OGG_VORBIS_MODE_1 = 0x674F
OGG_VORBIS_MODE_2 = 0x6750
OGG_VORBIS_MODE_3 = 0x6751
OGG_VORBIS_MODE_1_PLUS = 0x676F
OGG_VORBIS_MODE_2_PLUS = 0x6770
OGG_VORBIS_MODE_3_PLUS = 0x6771
ALAC = 0x6C61
_3COM_NBX = 0x7000 # Can't have leading digit
OPUS = 0x704F
FAAD_AAC = 0x706D
AMR_NB = 0x7361
AMR_WB = 0x7362
AMR_WP = 0x7363
GSM_AMR_CBR = 0x7A21
GSM_AMR_VBR_SID = 0x7A22
COMVERSE_INFOSYS_G723_1 = 0xA100
COMVERSE_INFOSYS_AVQSBC = 0xA101
COMVERSE_INFOSYS_SBC = 0xA102
SYMBOL_G729_A = 0xA103
VOICEAGE_AMR_WB = 0xA104
INGENIENT_G726 = 0xA105
MPEG4_AAC = 0xA106
ENCORE_G726 = 0xA107
ZOLL_ASAO = 0xA108
SPEEX_VOICE = 0xA109
VIANIX_MASC = 0xA10A
WM9_SPECTRUM_ANALYZER = 0xA10B
WMF_SPECTRUM_ANAYZER = 0xA10C
GSM_610 = 0xA10D
GSM_620 = 0xA10E
GSM_660 = 0xA10F
GSM_690 = 0xA110
GSM_ADAPTIVE_MULTIRATE_WB = 0xA111
POLYCOM_G722 = 0xA112
POLYCOM_G728 = 0xA113
POLYCOM_G729_A = 0xA114
POLYCOM_SIREN = 0xA115
GLOBAL_IP_ILBC = 0xA116
RADIOTIME_TIME_SHIFT_RADIO = 0xA117
NICE_ACA = 0xA118
NICE_ADPCM = 0xA119
VOCORD_G721 = 0xA11A
VOCORD_G726 = 0xA11B
VOCORD_G722_1 = 0xA11C
VOCORD_G728 = 0xA11D
VOCORD_G729 = 0xA11E
VOCORD_G729_A = 0xA11F
VOCORD_G723_1 = 0xA120
VOCORD_LBC = 0xA121
NICE_G728 = 0xA122
FRACE_TELECOM_G729 = 0xA123
CODIAN = 0xA124
FLAC = 0xF1AC
EXTENSIBLE = 0xFFFE
DEVELOPMENT = 0xFFFF
KNOWN_WAVE_FORMATS = {WAVE_FORMAT.PCM, WAVE_FORMAT.IEEE_FLOAT}
def _raise_bad_format(format_tag):
try:
format_name = WAVE_FORMAT(format_tag).name
except ValueError:
format_name = f'{format_tag:#06x}'
raise ValueError(f"Unknown wave file format: {format_name}. Supported "
"formats: " +
', '.join(x.name for x in KNOWN_WAVE_FORMATS))
def _read_fmt_chunk(fid, is_big_endian):
"""
Returns
-------
size : int
size of format subchunk in bytes (minus 8 for "fmt " and itself)
format_tag : int
PCM, float, or compressed format
channels : int
number of channels
fs : int
sampling frequency in samples per second
bytes_per_second : int
overall byte rate for the file
block_align : int
bytes per sample, including all channels
bit_depth : int
bits per sample
Notes
-----
Assumes file pointer is immediately after the 'fmt ' id
"""
if is_big_endian:
fmt = '>'
else:
fmt = '<'
size = struct.unpack(fmt+'I', fid.read(4))[0]
if size < 16:
raise ValueError("Binary structure of wave file is not compliant")
res = struct.unpack(fmt+'HHIIHH', fid.read(16))
bytes_read = 16
format_tag, channels, fs, bytes_per_second, block_align, bit_depth = res
if format_tag == WAVE_FORMAT.EXTENSIBLE and size >= (16+2):
ext_chunk_size = struct.unpack(fmt+'H', fid.read(2))[0]
bytes_read += 2
if ext_chunk_size >= 22:
extensible_chunk_data = fid.read(22)
bytes_read += 22
raw_guid = extensible_chunk_data[2+4:2+4+16]
# GUID template {XXXXXXXX-0000-0010-8000-00AA00389B71} (RFC-2361)
# MS GUID byte order: first three groups are native byte order,
# rest is Big Endian
if is_big_endian:
tail = b'\x00\x00\x00\x10\x80\x00\x00\xAA\x00\x38\x9B\x71'
else:
tail = b'\x00\x00\x10\x00\x80\x00\x00\xAA\x00\x38\x9B\x71'
if raw_guid.endswith(tail):
format_tag = struct.unpack(fmt+'I', raw_guid[:4])[0]
else:
raise ValueError("Binary structure of wave file is not compliant")
if format_tag not in KNOWN_WAVE_FORMATS:
_raise_bad_format(format_tag)
# move file pointer to next chunk
if size > bytes_read:
fid.read(size - bytes_read)
# fmt should always be 16, 18 or 40, but handle it just in case
_handle_pad_byte(fid, size)
if format_tag == WAVE_FORMAT.PCM:
if bytes_per_second != fs * block_align:
raise ValueError("WAV header is invalid: nAvgBytesPerSec must"
" equal product of nSamplesPerSec and"
" nBlockAlign, but file has nSamplesPerSec ="
f" {fs}, nBlockAlign = {block_align}, and"
f" nAvgBytesPerSec = {bytes_per_second}")
return (size, format_tag, channels, fs, bytes_per_second, block_align,
bit_depth)
def _read_data_chunk(fid, format_tag, channels, bit_depth, is_big_endian,
block_align, mmap=False):
"""
Notes
-----
Assumes file pointer is immediately after the 'data' id
It's possible to not use all available bits in a container, or to store
samples in a container bigger than necessary, so bytes_per_sample uses
the actual reported container size (nBlockAlign / nChannels). Real-world
examples:
Adobe Audition's "24-bit packed int (type 1, 20-bit)"
nChannels = 2, nBlockAlign = 6, wBitsPerSample = 20
http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Samples/AFsp/M1F1-int12-AFsp.wav
is:
nChannels = 2, nBlockAlign = 4, wBitsPerSample = 12
http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/Docs/multichaudP.pdf
gives an example of:
nChannels = 2, nBlockAlign = 8, wBitsPerSample = 20
"""
if is_big_endian:
fmt = '>'
else:
fmt = '<'
# Size of the data subchunk in bytes
size = struct.unpack(fmt+'I', fid.read(4))[0]
# Number of bytes per sample (sample container size)
bytes_per_sample = block_align // channels
n_samples = size // bytes_per_sample
if format_tag == WAVE_FORMAT.PCM:
if 1 <= bit_depth <= 8:
dtype = 'u1' # WAV of 8-bit integer or less are unsigned
elif bytes_per_sample in {3, 5, 6, 7}:
# No compatible dtype. Load as raw bytes for reshaping later.
dtype = 'V1'
elif bit_depth <= 64:
# Remaining bit depths can map directly to signed numpy dtypes
dtype = f'{fmt}i{bytes_per_sample}'
else:
raise ValueError("Unsupported bit depth: the WAV file "
f"has {bit_depth}-bit integer data.")
elif format_tag == WAVE_FORMAT.IEEE_FLOAT:
if bit_depth in {32, 64}:
dtype = f'{fmt}f{bytes_per_sample}'
else:
raise ValueError("Unsupported bit depth: the WAV file "
f"has {bit_depth}-bit floating-point data.")
else:
_raise_bad_format(format_tag)
start = fid.tell()
if not mmap:
try:
count = size if dtype == 'V1' else n_samples
data = numpy.fromfile(fid, dtype=dtype, count=count)
except io.UnsupportedOperation: # not a C-like file
fid.seek(start, 0) # just in case it seeked, though it shouldn't
data = numpy.frombuffer(fid.read(size), dtype=dtype)
if dtype == 'V1':
# Rearrange raw bytes into smallest compatible numpy dtype
dt = f'{fmt}i4' if bytes_per_sample == 3 else f'{fmt}i8'
a = numpy.zeros((len(data) // bytes_per_sample, numpy.dtype(dt).itemsize),
dtype='V1')
if is_big_endian:
a[:, :bytes_per_sample] = data.reshape((-1, bytes_per_sample))
else:
a[:, -bytes_per_sample:] = data.reshape((-1, bytes_per_sample))
data = a.view(dt).reshape(a.shape[:-1])
else:
if bytes_per_sample in {1, 2, 4, 8}:
start = fid.tell()
data = numpy.memmap(fid, dtype=dtype, mode='c', offset=start,
shape=(n_samples,))
fid.seek(start + size)
else:
raise ValueError("mmap=True not compatible with "
f"{bytes_per_sample}-byte container size.")
_handle_pad_byte(fid, size)
if channels > 1:
data = data.reshape(-1, channels)
return data
def _skip_unknown_chunk(fid, is_big_endian):
if is_big_endian:
fmt = '>I'
else:
fmt = '<I'
data = fid.read(4)
# call unpack() and seek() only if we have really read data from file
# otherwise empty read at the end of the file would trigger
# unnecessary exception at unpack() call
# in case data equals somehow to 0, there is no need for seek() anyway
if data:
size = struct.unpack(fmt, data)[0]
fid.seek(size, 1)
_handle_pad_byte(fid, size)
def _read_riff_chunk(fid):
str1 = fid.read(4) # File signature
if str1 == b'RIFF':
is_big_endian = False
fmt = '<I'
elif str1 == b'RIFX':
is_big_endian = True
fmt = '>I'
else:
# There are also .wav files with "FFIR" or "XFIR" signatures?
raise ValueError(f"File format {repr(str1)} not understood. Only "
"'RIFF' and 'RIFX' supported.")
# Size of entire file
file_size = struct.unpack(fmt, fid.read(4))[0] + 8
str2 = fid.read(4)
if str2 != b'WAVE':
raise ValueError(f"Not a WAV file. RIFF form type is {repr(str2)}.")
return file_size, is_big_endian
def _handle_pad_byte(fid, size):
# "If the chunk size is an odd number of bytes, a pad byte with value zero
# is written after ckData." So we need to seek past this after each chunk.
if size % 2:
fid.seek(1, 1)
def read(filename, mmap=False):
"""
Open a WAV file.
Return the sample rate (in samples/sec) and data from an LPCM WAV file.
Parameters
----------
filename : string or open file handle
Input WAV file.
mmap : bool, optional
Whether to read data as memory-mapped (default: False). Not compatible
with some bit depths; see Notes. Only to be used on real files.
.. versionadded:: 0.12.0
Returns
-------
rate : int
Sample rate of WAV file.
data : numpy array
Data read from WAV file. Data-type is determined from the file;
see Notes. Data is 1-D for 1-channel WAV, or 2-D of shape
(Nsamples, Nchannels) otherwise. If a file-like input without a
C-like file descriptor (e.g., :class:`python:io.BytesIO`) is
passed, this will not be writeable.
Notes
-----
Common data types: [1]_
===================== =========== =========== =============
WAV format Min Max NumPy dtype
===================== =========== =========== =============
32-bit floating-point -1.0 +1.0 float32
32-bit integer PCM -2147483648 +2147483647 int32
24-bit integer PCM -2147483648 +2147483392 int32
16-bit integer PCM -32768 +32767 int16
8-bit integer PCM 0 255 uint8
===================== =========== =========== =============
WAV files can specify arbitrary bit depth, and this function supports
reading any integer PCM depth from 1 to 64 bits. Data is returned in the
smallest compatible numpy int type, in left-justified format. 8-bit and
lower is unsigned, while 9-bit and higher is signed.
For example, 24-bit data will be stored as int32, with the MSB of the
24-bit data stored at the MSB of the int32, and typically the least
significant byte is 0x00. (However, if a file actually contains data past
its specified bit depth, those bits will be read and output, too. [2]_)
This bit justification and sign matches WAV's native internal format, which
allows memory mapping of WAV files that use 1, 2, 4, or 8 bytes per sample
(so 24-bit files cannot be memory-mapped, but 32-bit can).
IEEE float PCM in 32- or 64-bit format is supported, with or without mmap.
Values exceeding [-1, +1] are not clipped.
Non-linear PCM (mu-law, A-law) is not supported.
References
----------
.. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
Interface and Data Specifications 1.0", section "Data Format of the
Samples", August 1991
http://www.tactilemedia.com/info/MCI_Control_Info.html
.. [2] Adobe Systems Incorporated, "Adobe Audition 3 User Guide", section
"Audio file formats: 24-bit Packed Int (type 1, 20-bit)", 2007
Examples
--------
>>> from os.path import dirname, join as pjoin
>>> from scipy.io import wavfile
>>> import scipy.io
Get the filename for an example .wav file from the tests/data directory.
>>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data')
>>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')
Load the .wav file contents.
>>> samplerate, data = wavfile.read(wav_fname)
>>> print(f"number of channels = {data.shape[1]}")
number of channels = 2
>>> length = data.shape[0] / samplerate
>>> print(f"length = {length}s")
length = 0.01s
Plot the waveform.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> time = np.linspace(0., length, data.shape[0])
>>> plt.plot(time, data[:, 0], label="Left channel")
>>> plt.plot(time, data[:, 1], label="Right channel")
>>> plt.legend()
>>> plt.xlabel("Time [s]")
>>> plt.ylabel("Amplitude")
>>> plt.show()
"""
if hasattr(filename, 'read'):
fid = filename
mmap = False
else:
fid = open(filename, 'rb')
try:
file_size, is_big_endian = _read_riff_chunk(fid)
fmt_chunk_received = False
data_chunk_received = False
while fid.tell() < file_size:
# read the next chunk
chunk_id = fid.read(4)
if not chunk_id:
if data_chunk_received:
# End of file but data successfully read
warnings.warn(
"Reached EOF prematurely; finished at {:d} bytes, "
"expected {:d} bytes from header."
.format(fid.tell(), file_size),
WavFileWarning, stacklevel=2)
break
else:
raise ValueError("Unexpected end of file.")
elif len(chunk_id) < 4:
msg = f"Incomplete chunk ID: {repr(chunk_id)}"
# If we have the data, ignore the broken chunk
if fmt_chunk_received and data_chunk_received:
warnings.warn(msg + ", ignoring it.", WavFileWarning,
stacklevel=2)
else:
raise ValueError(msg)
if chunk_id == b'fmt ':
fmt_chunk_received = True
fmt_chunk = _read_fmt_chunk(fid, is_big_endian)
format_tag, channels, fs = fmt_chunk[1:4]
bit_depth = fmt_chunk[6]
block_align = fmt_chunk[5]
elif chunk_id == b'fact':
_skip_unknown_chunk(fid, is_big_endian)
elif chunk_id == b'data':
data_chunk_received = True
if not fmt_chunk_received:
raise ValueError("No fmt chunk before data")
data = _read_data_chunk(fid, format_tag, channels, bit_depth,
is_big_endian, block_align, mmap)
elif chunk_id == b'LIST':
# Someday this could be handled properly but for now skip it
_skip_unknown_chunk(fid, is_big_endian)
elif chunk_id in {b'JUNK', b'Fake'}:
# Skip alignment chunks without warning
_skip_unknown_chunk(fid, is_big_endian)
else:
warnings.warn("Chunk (non-data) not understood, skipping it.",
WavFileWarning, stacklevel=2)
_skip_unknown_chunk(fid, is_big_endian)
finally:
if not hasattr(filename, 'read'):
fid.close()
else:
fid.seek(0)
return fs, data
def write(filename, rate, data):
"""
Write a NumPy array as a WAV file.
Parameters
----------
filename : string or open file handle
Output wav file.
rate : int
The sample rate (in samples/sec).
data : ndarray
A 1-D or 2-D NumPy array of either integer or float data-type.
Notes
-----
* Writes a simple uncompressed WAV file.
* To write multiple-channels, use a 2-D array of shape
(Nsamples, Nchannels).
* The bits-per-sample and PCM/float will be determined by the data-type.
Common data types: [1]_
===================== =========== =========== =============
WAV format Min Max NumPy dtype
===================== =========== =========== =============
32-bit floating-point -1.0 +1.0 float32
32-bit PCM -2147483648 +2147483647 int32
16-bit PCM -32768 +32767 int16
8-bit PCM 0 255 uint8
===================== =========== =========== =============
Note that 8-bit PCM is unsigned.
References
----------
.. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
Interface and Data Specifications 1.0", section "Data Format of the
Samples", August 1991
http://www.tactilemedia.com/info/MCI_Control_Info.html
Examples
--------
Create a 100Hz sine wave, sampled at 44100Hz.
Write to 16-bit PCM, Mono.
>>> from scipy.io.wavfile import write
>>> samplerate = 44100; fs = 100
>>> t = np.linspace(0., 1., samplerate)
>>> amplitude = np.iinfo(np.int16).max
>>> data = amplitude * np.sin(2. * np.pi * fs * t)
>>> write("example.wav", samplerate, data.astype(np.int16))
"""
if hasattr(filename, 'write'):
fid = filename
else:
fid = open(filename, 'wb')
fs = rate
try:
dkind = data.dtype.kind
if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and
data.dtype.itemsize == 1)):
raise ValueError("Unsupported data type '%s'" % data.dtype)
header_data = b''
header_data += b'RIFF'
header_data += b'\x00\x00\x00\x00'
header_data += b'WAVE'
# fmt chunk
header_data += b'fmt '
if dkind == 'f':
format_tag = WAVE_FORMAT.IEEE_FLOAT
else:
format_tag = WAVE_FORMAT.PCM
if data.ndim == 1:
channels = 1
else:
channels = data.shape[1]
bit_depth = data.dtype.itemsize * 8
bytes_per_second = fs*(bit_depth // 8)*channels
block_align = channels * (bit_depth // 8)
fmt_chunk_data = struct.pack('<HHIIHH', format_tag, channels, fs,
bytes_per_second, block_align, bit_depth)
if not (dkind == 'i' or dkind == 'u'):
# add cbSize field for non-PCM files
fmt_chunk_data += b'\x00\x00'
header_data += struct.pack('<I', len(fmt_chunk_data))
header_data += fmt_chunk_data
# fact chunk (non-PCM files)
if not (dkind == 'i' or dkind == 'u'):
header_data += b'fact'
header_data += struct.pack('<II', 4, data.shape[0])
# check data size (needs to be immediately before the data chunk)
if ((len(header_data)-4-4) + (4+4+data.nbytes)) > 0xFFFFFFFF:
raise ValueError("Data exceeds wave file size limit")
fid.write(header_data)
# data chunk
fid.write(b'data')
fid.write(struct.pack('<I', data.nbytes))
if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and
sys.byteorder == 'big'):
data = data.byteswap()
_array_tofile(fid, data)
# Determine file size and place it in correct
# position at start of the file.
size = fid.tell()
fid.seek(4)
fid.write(struct.pack('<I', size-8))
finally:
if not hasattr(filename, 'write'):
fid.close()
else:
fid.seek(0)
def _array_tofile(fid, data):
# ravel gives a c-contiguous buffer
fid.write(data.ravel().view('b').data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment