def init_config(self): """Read and parse configuration.""" filename = "config.json" # setup config file: self.my_config = ConfigDict(self.config_defaults, filename) # print("my_config.config: {}".format(self.my_config.config)) self.config = self.my_config.config
def __init__(self, filename): """init.""" self.ablib_available = False global ablib_available print(" ablib_available:{}".format(ablib_available)) print(" self.ablib_available:{}".format(self.ablib_available)) self.ablib_available = ablib_available print(" self.ablib_available:{}".format(self.ablib_available)) # read config file: self.my_config = ConfigDict(self.default_config, filename) # print("my_config.config: {}".format(self.my_config.config)) self.config = self.my_config.config # print("config: {}".format(self.config)) self._init_lcd() self.flag_run = False # setup termination and interrupt handling: signal.signal(signal.SIGINT, self._exit_helper) signal.signal(signal.SIGTERM, self._exit_helper)
from configdict import ConfigDict import sys import ctcsound config = ConfigDict("emlib:synthplayer", default={ 'sr': 44100, 'linux.backend': 'jack', 'multisine.maxosc': 200, }, validator={'linux.backend::choices': ['jack', 'portaudi']}) _csd_multisine = ''' sr = {sr} ksmps = {ksmps} nchnls = 2 0dbfs = 1 #define MAXPARTIALS #{numosc}# gkFreqs[] init $MAXPARTIALS gkAmps[] init $MAXPARTIALS gkBws[] init $MAXPARTIALS gkgain init 1 alwayson 2, {numosc} schedule 1, 0, 1 instr 1
'ksmps': 64, 'linux.backend': 'jack', 'A4': 442, 'multisine.maxosc': 200, } _validator = { 'linux.backend::choices': ['jack', 'pa_cb'], 'numchannels::range': (1, 128), 'sr::choices': [0, 22050, 24000, 44100, 48000, 88200, 96000], 'ksmps::choices': [16, 32, 64, 128, 256], 'A4::range': (410, 460) } config = ConfigDict("emlib:synthplayer", default=_defaultconfig, validator=_validator) class CsdInstrError(ValueError): pass class _SynthDef(NamedTuple): qname: str instrnum: int _MYFLTPTR = ctypes.POINTER(ctcsound.MYFLT) _csound_reserved_instrnum = 100
def setLoggingLevel(level: str) -> None: """ Utility to set the logging level of csoundengine """ level = level.upper() logging.basicConfig(level=level) logger.setLevel(level) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # CONFIG # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # config = ConfigDict(modulename) _ = config.addKey _audioBackendsByPlatform = { 'linux': ('jack', 'alsa', 'pa_cb', 'pa_bl', 'pulse'), 'macos': ('auhal', 'pa_cb', 'pa_bl', 'jack'), 'windows': ('pa_cb', 'pa_bl') } @lru_cache(maxsize=0) def _validateBackend2(key: str, s: str) -> bool: platform = key.split("_")[0] possibleBackends = _audioBackendsByPlatform.get(platform) if not possibleBackends: logger.error(f"Platform {platform} not supported, no audio backends")
'for a next session', 'play.unknownParameterFailSilently': 'If True, any attempt to set an unknown parameter will be silently ignored', 'splitAcceptableDeviation': 'When splitting notes between staves, notes within this range of the ' 'split point will be grouped together if they all fit', 'play.autostartEngine': 'Start play engine if not started manually. This is done when the user' 'performs an action which indirectly needs the engine to be running,' 'like defining an instrument, or calling play.getPlayManager()', 'rec.quiet': 'Supress debug output when calling csound as a subprocess' } config = ConfigDict(f'maelzel:core', _default, validator=_validator, docs=_docs) @lru_cache(maxsize=1) def _presetsPath() -> str: datadirbase = appdirs.user_data_dir("maelzel") path = os.path.join(datadirbase, "core", "presets") return path def presetsPath() -> str: """ Returns the path of the presets directory """ userpath = config['play.presetsPath'] if userpath: return userpath
_home = os.path.expanduser("~") def _isofmt(t: datetime) -> str: """Returns the time in iso format""" return t.isoformat(':', 'minutes') _defaultState = { 'last_run': datetime(1900, 1, 1).isoformat(), 'soundfont_last_dir': _home, 'soundfile_last_dir': _home, } state = ConfigDict("csoundengine.state", _defaultState) def openFile(key, filter="All (*.*)", title="Open File"): folder = state[key] f = emlib.dialogs.selectFile(directory=folder, filter=filter, title=title) if f: folder = os.path.split(f)[0] state[key] = folder return f def saveFile(key, filter="All (*.*)", title="Save File"): folder = state[key] f = emlib.dialogs.saveDialog(directory=folder, filter=filter, title=title) if f:
logger = logging.getLogger("maelzel.audiosample") _initWasDone = False def _configCheck(config, key, oldvalue, newvalue): if key == 'editor': if os.path.exists(newvalue) or shutil.which(newvalue): return oldvalue logger.error(f"Trying to set editor to {newvalue}." " File not found") return oldvalue config = ConfigDict(name='maelzel:audiosample', default={ 'editor': 'audacity', 'fade.shape': 'linear', }, precallback=_configCheck) def _increase_suffix(filename: str) -> str: name, ext = os.path.splitext(filename) tokens = name.split("-") newname = None if len(tokens) > 1: suffix = tokens[-1] try: suffixnum = int(suffix) newname = f"{name[:-len(suffix)]}-{suffixnum + 1}" except ValueError: pass
from emlib import numpytools from scipy import signal import numpy as np from configdict import ConfigDict def _get_cmaps(): import matplotlib.pyplot as plt return plt.colormaps() config = ConfigDict("emlib:snd_plotting", default={'spectrogram_colormap': 'inferno'}, validator={'spectrogram_colormap::choices': _get_cmaps}) def plot_power_spectrum(samples, samplerate, framesize=2048, window=('kaiser', 9)): """ Args: samples: the samples to plot samplerate: the samplerate of thesamples framesize: the bigger the frame size, the smoother the plot window: As passed to scipy.signal.get_window `blackman`, `hamming`, `hann`, `bartlett`, `flattop`, `parzen`, `bohman`, `blackmanharris`, `nuttall`, `barthann`, `kaiser` (needs beta), `gaussian` (needs standard deviation)
2, 3, 0, 1, ], 'repeat': 5, 'repeat_reverse': True, 'offset': True, 'offset_count': 32, }, } my_config = ConfigDict(default_config, filename) print("my_config.config: {}".format(my_config.config)) my_mapper = OLAMapper(my_config.config) print("full map:\n{}".format(my_mapper.map_tostring_pretty())) my_mapper.start_ola() # wait for user to hit key. try: raw_input("\n\n" + 42 * '*' + "\nhit a key to stop the mapper\n" + 42 * '*' + "\n\n") except KeyboardInterrupt: print("\nstop.") except: print("\nstop.")
class LCDManager(): """Main Class.""" default_config = { 'lcd_address': 0x27, 'show': { 'line1': ':-)', }, } def __init__(self, filename): """init.""" self.ablib_available = False global ablib_available print(" ablib_available:{}".format(ablib_available)) print(" self.ablib_available:{}".format(self.ablib_available)) self.ablib_available = ablib_available print(" self.ablib_available:{}".format(self.ablib_available)) # read config file: self.my_config = ConfigDict(self.default_config, filename) # print("my_config.config: {}".format(self.my_config.config)) self.config = self.my_config.config # print("config: {}".format(self.config)) self._init_lcd() self.flag_run = False # setup termination and interrupt handling: signal.signal(signal.SIGINT, self._exit_helper) signal.signal(signal.SIGTERM, self._exit_helper) def __del__(self): """Clean up.""" # print a goodby message: if self.ablib_available: self.lcd.setcurpos(0, 0) self.lcd.putstring('See you :-)') pass def _exit_helper(self): """Stop loop.""" self.flag_run = True ########################################## # def config_print(self): """Print configuration.""" print("config: \n{}".format(self.my_config.get_formated())) # print(42*'*') ########################################## # def _init_lcd(self): print("init lcd:") if self.ablib_available: print("ablib available.") try: if ablib.existI2Cdevice(0, self.config['lcd_address']): i2c_address = self.config['lcd_address'] else: i2c_address = 0x3F print(" i2c_address:{}".format(i2c_address)) self.lcd = ablib.Daisy24(0, i2c_address) print(" lcd:{}".format(self.lcd)) except Exception as e: raise print(""" Check to run your script with SUDO.""") ablib_available = False else: print("ablib missing!!!!!!!") def _write_lcd(self): if self.ablib_available: self.lcd.setcurpos(0, 0) self.lcd.putstring('Hello World :-)') # '-----_____-----_' # '10.05. 12:00:00' timestring = time.strftime("%d.%m. %H:%M:%S") self.lcd.setcurpos(0, 1) self.lcd.putstring(timestring) # self.lcd.putstring('sunshine :-)') def system_run(self): """Run Main Loop.""" print("Start Main Loop: TODO!!!") self.flag_run = True try: while self.flag_run: self._write_lcd() time.sleep(0.5) except KeyboardInterrupt: print("\nstop script.") self.flag_run = False