"""Offline sampler for the bundled CC0 VSCO CE recordings. Requires numpy and ffmpeg.""" from pathlib import Path from functools import lru_cache import json, subprocess import numpy as np SR = 44100 SOURCES = Path(__file__).resolve().parent / 'SourceSamples~' @lru_cache(None) def source(name): raw = subprocess.check_output(['ffmpeg','-v','error','-i',str(SOURCES/name),'-f','f32le','-ar',str(SR),'-ac','1','pipe:1']) y = np.frombuffer(raw,dtype=' peak*.012) if len(first): y = y[max(0,first[0]-round(.004*SR)):] y -= np.mean(y) return y / peak def soften(y, attack=.003, release=.10): a=min(len(y),round(attack*SR)); r=min(len(y),round(release*SR)) if a: y[:a] *= np.linspace(0,1,a) if r: y[-r:] *= np.linspace(1,0,r) return y def sample(name, seconds, semitones=0): raw=source(name) positions=np.arange(0,min(len(raw)-1,seconds*SR*2**(semitones/12)),2**(semitones/12)) y=np.interp(positions,np.arange(len(raw)),raw) y=np.convolve(y,np.ones(5)/5,mode='same') return soften(y) def note(instrument,midi,seconds): records=json.loads((SOURCES/'sources.json').read_text())['files'] record=min((x for x in records if x['file'].startswith(instrument)),key=lambda x:abs(x['midi']-midi)) return sample(record['file'],seconds,midi-record['midi'])