def __init__(self, score_path, buffer_size=512, sample_rate=44100): Mixer.__init__(self) self.sample_rate = sample_rate self.buffer_size = buffer_size self.speed = self.DEFAULT_SPEED self.measure_resolution = self.DEFAULT_MEASURE_RESOLUTION self.beats_per_measure = self.DEFAULT_BEATS_PER_MEASURE self._update_sleep_interval() self.stress_gain = self.DEFAULT_STRESS_GAIN self.non_stress_gain = self.DEFAULT_NON_STRESS_GAIN self.current_gain = 1. self.running = False self.loop = 0 self.sleep_interval = None self.total_frame_count = 0 self.sleep_frames = 0 self.instruments = [] self.instrument_id_counter = 0 self.tracks = [] # Load score file data = open(score_path, 'r').read() self._parse(data) self.observers = set()
def test_make_proof(self): wrapper = Mixer(NATIVE_LIB_PATH, VK_PATH, PK_PATH) tree_depth = wrapper.tree_depth n_items = 2 << (tree_depth - 1) tree = MerkleTree(n_items) for n in range(0, 2): tree.append(int(FQ.random())) wallet_address = int(FQ.random()) nullifier_secret = int(FQ.random()) nullifier_hash = mimc_hash([nullifier_secret, nullifier_secret]) leaf_hash = int( get_sha256_hash(to_hex(nullifier_secret), to_hex(wallet_address)), 16) leaf_idx = tree.append(leaf_hash) self.assertEqual(leaf_idx, tree.index(leaf_hash)) # Verify it exists in true leaf_proof = tree.proof(leaf_idx) self.assertTrue(leaf_proof.verify(tree.root)) # Generate proof snark_proof = wrapper.prove( tree.root, wallet_address, nullifier_hash, nullifier_secret, # (index)_2 bits reversed, i.e. [LSB, ... , MSB] leaf_proof.address, leaf_proof.path) self.assertTrue(wrapper.verify(snark_proof))
def __init__(self, samplerate, bufferSize, scale): Mixer.__init__(self) self.instrument01 = MonophonicScaleSynth(samplerate, bufferSize, scale) self.instrument02 = SineSynth(samplerate, bufferSize) self.instrument03 = SineSynth(samplerate, bufferSize) self.add_device(self.instrument01) self.add_device(self.instrument02) self.add_device(self.instrument03) self.tone = None
def playit(self,file): os.system('clear') "Playing..." playing = Mixer(file) playing.mixer() os.system('clear') print "Done." pass pass
def __init__(self, buffer_size=512, sample_rate=44100, speed=DEFAULT_SPEED): Mixer.__init__(self) self.sample_rate = sample_rate self.buffer_size = buffer_size self.start_time = 0 self.speed = speed self.instruments = []
def __init__(self, characters): """Initialize all attributes and music. utils -- SpriteGroup, contains background and timer players -- SpriteGroup, contains two characters skills -- SkillManager, contains the skills of both characters """ SpriteGroup.__init__(self) self.background = Background(random.choice(glob. glob("assets/fields/*"))) self.mana_time = 0 self.timer = Timer() self.timer.position = Vec2D(DEFAULT_SCREEN_SIZE[0] / 2, 30) self.mixer = Mixer(glob.glob("assets/sound/play_menu/*")) self.mixer.play_random() self.player1 = Character(1, characters[0], (0, 0)) self.player2 = Character(2, characters[1], DEFAULT_SCREEN_SIZE) self.skills = SkillManager(self.player1.skills, self.player2.skills) self.players = SpriteGroup(self.player1, self.player2) self.utils = SpriteGroup(self.background, self.timer) self.add(self.utils, self.players, self.skills)
def __init__(self): persistent_attrs_init(self) self.synth = Fluidsynth() logging.debug("...") # 16 channels. One DeviceChain for each channel. Each # DeviceChain has a `Latch` and `Arpeggiator` self.devicechains = [DeviceChain(self, i) for i in range(16)] ## The root of all notes. self.key = notes.A logging.debug("...") self.grids = [] self.scale = [0, 3, 6, 7, 10] self.cpu = CPU(self) self.clock = Clock(self) self.looper = Looper(self) self.mixer = Mixer(self) self.detect_devices() # FIXME: probably make this configurable somehow (env var...?) if False: from termpad import ASCIIGrid self.grids.append(ASCIIGrid(self, 0, 1))
def callback(self, in_data, frame_count, time_info, status): if self.running: self.update(frame_count) res = Mixer.callback(self, in_data, frame_count, time_info, status) if res is None: return res else: return res * self.current_gain
def __init__(self): """Class constructor. Loads everything into memory """ self.display = pg.display.set_mode((640, 360)) pg.display.set_caption("Crawler") pg.init() self.level_list = None self.gui = Gui((640, 360)) self.level_id = 0 self.level = None self.event_queue = EventQueue() self.clock = Clock() self.renderer = Renderer(self.display, self.level, self.gui) self.mixer = Mixer() self.mixer.load_track(0) self.mixer.set_volume(0.3) self.game_loop = None self.menu_loop = MenuLoop(self.renderer, self.event_queue, self.clock) self.start_menu()
def __init__(self): persistent_attrs_init(self) self.synth = Fluidsynth() self.devicechains = [DeviceChain(self, i) for i in range(16)] self.grids = [] self.cpu = CPU(self) self.clock = Clock(self) self.looper = Looper(self) self.mixer = Mixer(self) # FIXME: probably make this configurable somehow (env var...?) if False: from termpad import ASCIIGrid self.grids.append(ASCIIGrid(self, 0, 1))
def __init__(self, display: Display): self.__mixer = Mixer() # precaution initial muting self.__mixer.mute() self.__stateFile = StateFile() self.__display = display self.__showInitInfo() self.__cdIsOver = False self.__mpv = MyMPV(self) self.__selectedSource = None self.__extConfig = self.__initExtConfig() # initial mute - arduino will send proper volumecommand # initial mute - arduino will send proper volumecommand # self.__switchToRadio() radioSource = RadioSource(display, self.__extConfig, self.__stateFile, self.__mixer, self) self.__cdSource = CDSource(display, self.__extConfig, self.__stateFile, self.__mixer, self) flashSource = FlashSource(display, self.__extConfig, self.__stateFile, self.__mixer, self) self.__sources = [radioSource, flashSource, self.__cdSource] self.__ringSources = cycle(self.__sources) self.switch()
def __init__( self, freq=440.0, level=1.0, phase=0.0, feedback=0, wave_type='sine', fm_type='DX', gate=Gate([0.0]), key_in=None ): Oscillator.__init__(self, key_in) self.freq = freq #frequency self.mixer = Mixer() #mixer to add modulators' outputs #sound generator if fm_type == 'LinearFM': self.generator = LinearFMGenerator( freq, level, phase, wave_type, self.mixer, key_in ) elif fm_type == 'DX': self.generator = DXGenerator( freq, level, phase, wave_type, self.mixer, key_in ) self.eg = ADSR(input=gate) #envelope generator #amplifier self.amp = Amplifier(input=self.generator, mod=self.eg)
def __init__(self, input_bits=12, output_bits=16, phaseinc_bits=18, nco_bits=18, if_bits=20): self.i_sample = Signal((input_bits, True)) self.o_i = Signal((output_bits, True)) self.o_q = Signal((output_bits, True)) self.o_valid = Signal() self.i_nco_freq = Signal(phaseinc_bits) self.input_bits = input_bits self.output_bits = output_bits self.phase_bits = phaseinc_bits self.if_bits = if_bits self.nco_bits = nco_bits self.nco = nco = NCO(output_bits=nco_bits, phaseinc_bits=phaseinc_bits) self.mixer = mixer = Mixer(sample_bits=input_bits, nco_bits=nco_bits, output_bits=if_bits) self.cic_i = cic_i = CIC(input_bits=if_bits) self.cic_q = cic_q = CIC(input_bits=if_bits) self.comb += [ mixer.i_sample.eq(self.i_sample), mixer.i_nco_i.eq(nco.o_nco_i), mixer.i_nco_q.eq(nco.o_nco_q), cic_i.i_sample.eq(mixer.o_i), cic_q.i_sample.eq(mixer.o_q), self.o_valid.eq(cic_i.o_valid), self.o_i.eq(cic_i.o_result[(cic_i.filter_bits - output_bits):]), self.o_q.eq(cic_q.o_result[(cic_q.filter_bits - output_bits):]) ] self.submodules += [ nco, mixer, cic_i, cic_q, ]
def mixer_process_function(): """This function is meant to be placed into is own process and loops in order to play the sounds without delay """ # Initialise the mixer and provide a callback to output to the GPIO port mixer = Mixer(lambda x: GPIO.output(consts.BUZZER_GPIO_CODE, x > 0.0)) time_old = time.time() while True: time_now = time.time() # Take from the queue and insert into the mixer while not consts.MIXER_QUEUE.empty(): mixer.insert(*consts.MIXER_QUEUE.get()) time_delta = time_now - time_old # Sample the mixer to provide output mixer.sample(time_delta) time_old = time_now
def select_atoms(self, atoms): subset = None subset_map = {} subset_weights = [] k = 0 ids = Mixer.get_atom_ids(atoms) for i in range(len(atoms)): if ids[i] not in self._atom_ids: continue if not subset: subset = Atoms(atoms[i:i+1]) else: subset.extend(atoms[i:i+1]) subset_map[k] = i subset_weights.append(self._weights[ids[i]]) k += 1 wa = np.zeros((len(subset_weights), 3)) for i in range(len(subset_weights)): wa[i] += subset_weights[i] return subset, subset_map, wa
def select_atoms(self, atoms): subset = None subset_map = {} subset_weights = [] k = 0 ids = Mixer.get_atom_ids(atoms) for i in range(len(atoms)): if ids[i] not in self._atom_ids: continue if not subset: subset = Atoms(atoms[i:i + 1]) else: subset.extend(atoms[i:i + 1]) subset_map[k] = i subset_weights.append(self._weights[ids[i]]) k += 1 wa = np.zeros((len(subset_weights), 3)) for i in range(len(subset_weights)): wa[i] += subset_weights[i] return subset, subset_map, wa
def select_atoms(self, atoms): """ Return an Atoms object containing only those from atoms that are within the CalcRegion and that don't have an interaction- chain to an atom outside the CalcRegion. This interaction-chain is a chain of atoms within cutoff distance from each other. @type atoms: Atoms @param atoms: the normal ASE Atoms object @rtype: (Atoms, dict, list) @return: Atoms provides an ASE Atoms object with the selected atoms. Dict contains a map, where map[i] gives the original index of Atoms[i]. List provides force calculation weights for each atom in Atoms. """ subset = None subset_map = {} weights = [] cutoff2 = self._cutoff**2 # use square for comparison with length2() p, d = self.get_bounding_box() # get the rectangular bounding box # create Octree with atoms inside or within cutoff distance from # CalcRegion root = OctreeNode(pos=p, dim=(d[0] + 2*self._cutoff, d[1] + 2*self._cutoff, d[2] + 2*self._cutoff), res=max(self._cutoff/2.0, 0.1)) atom_ids = Mixer.get_atom_ids(atoms) # extract atomids from atoms rev_map = {} # reverse map used to get from atom_ids to atoms[] indexes for i in range(len(atoms)): root.add_object(atom_ids[i], atoms[i].position) rev_map[atom_ids[i]] = i black_list = {} # blacklist of atoms with interaction-chain to outside for k in root.get_objects(): black_list[k] = False wrk = [] # stack for holding blacklisted atoms whose neighbours # need to be checked # populate wrk with those atoms outside CalcRegion that are still # within cutoff distance from it for atom_id in root.get_objects(): if self.atom_inside(atoms[rev_map[atom_id]].position): continue wrk.append(atom_id) black_list[atom_id] = True # loop until wrk is empty, any not-blacklisted neighbours within # cutoff distance from atoms that are blacklisted will be blacklisted # and pushed to wrk while len(wrk) > 0: atom_id = wrk.pop() # find neighbours approximately within cutoff ns = root.find_objects(atoms[rev_map[atom_id]].position, self._cutoff) for n in ns: if black_list[n]: # already blacklisted, ignore continue if (self.length2(atoms[rev_map[n]].position, atoms[rev_map[atom_id]].position) > cutoff2): # outside cutoff distance, ignore continue # not blacklisted, within cutoff, add to wrk # and blacklist wrk.append(n) black_list[n] = True k = 0 subset = Atoms() # construct cleaned up subset of atoms within the CalcRegion for atom_id in root.get_objects(): if black_list[atom_id]: # exclude blacklisted atom if self._debug > 2: print("excluding atom: %i" % atom_id) continue subset.extend(atoms[rev_map[atom_id]:rev_map[atom_id]+1]) weights.append( self.get_weight(atoms[rev_map[atom_id]].position)) subset_map[k] = rev_map[atom_id] k += 1 # create weights array that matches subset wa = np.zeros((len(weights), 3)) for i in range(len(weights)): wa[i] += weights[i] # set periodic boundary condition if self._pbc: subset.set_pbc(self._pbc) # dump CalcRegion contents to a trajectory file if debugging if self._debug_file != None: ase.io.pdb.write_pdb(self._debug_file, subset) return subset, subset_map, wa
def test_1(self): mixer1 = Mixer() out_v: int = mixer1.getvolume(out=True) in_v: int = mixer1.getvolume(out=False) mixer1.setvolume(33, out=True) mixer1.setvolume(23, out=False) self.assertEqual(mixer1.getvolume(out=True), 33) self.assertEqual(mixer1.getvolume(out=False), 23) mixer1.setvolume(out_v, out=True) mixer1.setvolume(in_v, out=False) mixer3 = Mixer() self.assertEqual(mixer3.getvolume(out=True), out_v) self.assertEqual(mixer3.getvolume(out=False), in_v)
# Entry point of the program - initializes mixer and client # Also for basic settings from mixer import Mixer from client import Client # Settings for testing ''' url = "broker.mqttdashboard.com" topic = "haw/dmi/mt/its/ss17/ambientbox" user = "" pw = "" ''' # Settings for HAW url = "diginet.mt.haw-hamburg.de" topic = "ambientbox" user = "******" pw = "schuh+-0" # Mixer Settings loopThreshold = 10 # Sounds shorter than this (seconds) will not be looped nonstop but rather be played in intervals depending on the volume of the channel maxLoopLength = 30 # Short sounds (see above) may be repeated at least every amount of seconds this is set to mixer = Mixer(loopThreshold, maxLoopLength) Client(url, topic, user, pw, mixer)
class Main: """The main game class, in charge of loading levels and handling features which are outside the game loop Attributes: display: a pygame display object level_list: list of levels level_id: id of the current level level: Level object event_queue: EventQueue object clock: a pygame clock object mixer: a mixer object """ def __init__(self): """Class constructor. Loads everything into memory """ self.display = pg.display.set_mode((640, 360)) pg.display.set_caption("Crawler") pg.init() self.level_list = None self.gui = Gui((640, 360)) self.level_id = 0 self.level = None self.event_queue = EventQueue() self.clock = Clock() self.renderer = Renderer(self.display, self.level, self.gui) self.mixer = Mixer() self.mixer.load_track(0) self.mixer.set_volume(0.3) self.game_loop = None self.menu_loop = MenuLoop(self.renderer, self.event_queue, self.clock) self.start_menu() def load_level_list(self): """Resets the level list from database """ self.level_list = DB_CONNECTION.get_map_data() def build_essentials(self): """A method which resets important objects for loading a different level """ self.load_level_list() self.load_level() self.gui = Gui((640, 360)) self.add_healthbars() self.renderer = Renderer(self.display, self.level, self.gui) self.game_loop = GameLoop(self.level, self.renderer, self.event_queue, self.clock, CELL_SIZE, self.gui, self.mixer) def load_level(self): """Loads a different level into memory """ self.level = Level(self.level_list[self.level_id], CELL_SIZE) def add_healthbars(self): """A method which adds health bars for all entities in a level """ for enemy in self.level.enemies: self.gui.set_health_bar(enemy) self.gui.set_player_health_bar(self.level.player) def load_level_id(self): """A method which fetches the level id of a saved game from a database """ data = DB_CONNECTION.get_player_data() if data: self.level_id = data[2] def load_player_data(self): """Loads a save game from a database """ data = DB_CONNECTION.get_player_data() if data: self.level.player.current_health = data[0] self.level.player.inventory = data[1] self.gui.set_player_health_bar(self.level.player) def store_player_data(self): """A method which stores player data into a database """ DB_CONNECTION.store_player_data(self.level.player, self.level_id) def start_menu(self): """Method which starts a menu loop and is the backbone of the game """ state = self.menu_loop.start() if state != -1: if state == 0: DB_CONNECTION.reset_player_data() self.level_id = 0 self.build_essentials() if state == 1 and not self.level: self.load_level_id() self.build_essentials() self.load_player_data() self.run() def run(self): """Method which starts the main game loop """ self.mixer.play_music(loops=-1) state = self.game_loop.start() if state == 1: self.start_menu() if state == 3: self.level_id += 1 if self.level_id == len(self.level_list): self.level_id = 0 self.store_player_data() self.build_essentials() self.load_player_data() self.run() if state == 4: DB_CONNECTION.reset_player_data() self.__init__()
from mixer import Mixer, get_from_list, shuffled_ints if __name__ == "__main__": fn = get_from_list("lists/firstnames.txt", 2) ln = get_from_list("lists/lastnames.txt", 3) mixer = Mixer() mixer.set_delimiter('|') mixer.add_column(fn) mixer.add_column(ln) mixer.add_column(shuffled_ints(1, 5)) print mixer.mix() mixer.add_record("")
N_COMPS = 5 unit_dict = dict() # instantiate the required objects condensate = Stream(n_comps=N_COMPS, name='Condensate') reflux = Stream(n_comps=N_COMPS, name='Reflux') top_product = Stream(n_comps=N_COMPS, name='Top product') bottoms = Stream(n_comps=N_COMPS, name='Bottoms') vapor_reboil = Stream(n_comps=N_COMPS, name='Vapor reboil') bottom_product = Stream(n_comps=N_COMPS, name='Bottom product') feed = Stream(n_comps=N_COMPS, name='LiquidFeed') condenser = Mixer(streams_in=[condensate], streams_out=[reflux, top_product], name='Condenser') reboiler = Mixer(streams_in=[bottoms], streams_out=[vapor_reboil, bottom_product], name='Reboiler') feed_flow_spec = Specify(flow=True, stream=feed, value=100) feed_temp_spec = Specify(temperature=True, stream=feed, value=100) feed_ic4_spec = Specify(fraction=True, stream=feed, comp_num=0, value=0.1) feed_nc4_spec = Specify(fraction=True, stream=feed, comp_num=1, value=0.3) feed_ic5_spec = Specify(fraction=True, stream=feed, comp_num=2, value=0.2) feed_nc5_spec = Specify(fraction=True, stream=feed, comp_num=3, value=0.3) feed_nc6_spec = Specify(fraction=True, stream=feed, comp_num=4, value=0.1) reflux_flow_spec = Specify(flow=True, stream=reflux, value=120) vapor_reboil_flow_spec = Specify(flow=True, stream=vapor_reboil, value=160) top_product_flow_spec = Specify(flow=True, stream=top_product, value=40) foust_8_11 = SimpleColumn(n_trays=15,
def setUp(self): # pygame.display.init() self.mixer = Mixer(glob.glob("assets/sound/play_menu/*"))
from mixer import Mixer, get_from_list, shuffled_ints, shuffled_decs if __name__ == "__main__": fn = get_from_list("lists/firstnames.txt") ln = get_from_list("lists/lastnames.txt") dates_f = get_from_list("lists/dates.txt") systems_f = get_from_list("lists/systems.txt") device_agents_f = get_from_list("lists/device_agents.txt") mixer = Mixer() mixer.set_delimiter('|') mixer.add_column(fn) mixer.add_column(ln) mixer.add_column(shuffled_ints(1, 5)) mixer.add_column(shuffled_ints(100, 250)) mixer.add_column(dates_f) mixer.add_column(systems_f) mixer.add_column(device_agents_f) mixer.add_column(dates_f) mixer.add_column(['\n']) print mixer.mix(number_of_records=100, with_incremental_id=False) with open('sample-data.txt', "w+") as f: f.writelines([ "first_name|last_name|count_num|amount|start_date|name_2|name_3|date_1|empty_col\n" ]) f.writelines( mixer.mix(number_of_records=100000, with_incremental_id=False))
for handler in logging.root.handlers: logging.root.removeHandler(handler) logging.root.addHandler(customlog.MultiprocessingStreamHandler()) log = logging.getLogger(config.log_name) log.info("Starting %s...", config.app_name) track_queue = multiprocessing.Queue(1) log.info("Initializing read queue to hold %2.2f seconds of audio.", config.frontend_buffer) v2_queue = BufferedReadQueue( int(config.frontend_buffer / SECONDS_PER_FRAME)) info_queue = multiprocessing.Queue() mixer = Mixer(iqueue=track_queue, oqueues=(v2_queue.raw, ), infoqueue=info_queue) mixer.start() if stream: import brain Hotswap(track_queue.put, brain).start() Hotswap(InfoHandler.add, info, 'generate', info_queue, first_frame).start() Hotswap(MonitorSocket.update, statistician, 'generate', lambda: StreamHandler.relays, InfoHandler.stats, mp3_queue=v2_queue).start() tornado.ioloop.PeriodicCallback(
def select_atoms(self, atoms): """ Return an Atoms object containing only those from atoms that are within the CalcRegion and that don't have an interaction- chain to an atom outside the CalcRegion. This interaction-chain is a chain of atoms within cutoff distance from each other. @type atoms: Atoms @param atoms: the normal ASE Atoms object @rtype: (Atoms, dict, list) @return: Atoms provides an ASE Atoms object with the selected atoms. Dict contains a map, where map[i] gives the original index of Atoms[i]. List provides force calculation weights for each atom in Atoms. """ subset = None subset_map = {} weights = [] cutoff2 = self._cutoff**2 # use square for comparison with length2() p, d = self.get_bounding_box() # get the rectangular bounding box # create Octree with atoms inside or within cutoff distance from # CalcRegion root = OctreeNode(pos=p, dim=(d[0] + 2 * self._cutoff, d[1] + 2 * self._cutoff, d[2] + 2 * self._cutoff), res=max(self._cutoff / 2.0, 0.1)) atom_ids = Mixer.get_atom_ids(atoms) # extract atomids from atoms rev_map = { } # reverse map used to get from atom_ids to atoms[] indexes for i in range(len(atoms)): root.add_object(atom_ids[i], atoms[i].position) rev_map[atom_ids[i]] = i black_list = {} # blacklist of atoms with interaction-chain to outside for k in root.get_objects(): black_list[k] = False wrk = [] # stack for holding blacklisted atoms whose neighbours # need to be checked # populate wrk with those atoms outside CalcRegion that are still # within cutoff distance from it for atom_id in root.get_objects(): if self.atom_inside(atoms[rev_map[atom_id]].position): continue wrk.append(atom_id) black_list[atom_id] = True # loop until wrk is empty, any not-blacklisted neighbours within # cutoff distance from atoms that are blacklisted will be blacklisted # and pushed to wrk while len(wrk) > 0: atom_id = wrk.pop() # find neighbours approximately within cutoff ns = root.find_objects(atoms[rev_map[atom_id]].position, self._cutoff) for n in ns: if black_list[n]: # already blacklisted, ignore continue if (self.length2(atoms[rev_map[n]].position, atoms[rev_map[atom_id]].position) > cutoff2): # outside cutoff distance, ignore continue # not blacklisted, within cutoff, add to wrk # and blacklist wrk.append(n) black_list[n] = True k = 0 subset = Atoms() # construct cleaned up subset of atoms within the CalcRegion for atom_id in root.get_objects(): if black_list[atom_id]: # exclude blacklisted atom if self._debug > 2: print("excluding atom: %i" % atom_id) continue subset.extend(atoms[rev_map[atom_id]:rev_map[atom_id] + 1]) weights.append(self.get_weight(atoms[rev_map[atom_id]].position)) subset_map[k] = rev_map[atom_id] k += 1 # create weights array that matches subset wa = np.zeros((len(weights), 3)) for i in range(len(weights)): wa[i] += weights[i] # set periodic boundary condition if self._pbc: subset.set_pbc(self._pbc) # dump CalcRegion contents to a trajectory file if debugging if self._debug_file != None: ase.io.pdb.write_pdb(self._debug_file, subset) return subset, subset_map, wa
def __init__(self, id_variable=None): Mixer.__init__(self) self.sub_instruments = {} self.observers = set() self.id_variable = id_variable self.name_id = self.name
def __init__(self, n_trays, feed_tray, feed_stream_liq, reflux, vapor_reboil, condensate, bottoms, pressure, tray_efficiency=1.0, name=None): ''' feed_tray must be an integer between 1 and n_trays-2 (feed cannot be to the top or bottom trays for now) the bottom tray is tray number zero the top tray is tray number n_trays-1 the default efficiency is 1 for all trays. if tray_efficiency is a scalar, it is used for all trays. if tray_efficiency is a dict (tray:efficiency), it is used for the specified trays. the remaining are assigned an efficiency of 1. ''' self.column_num = SimpleColumn.n_columns super().__init__(name, self.column_num) SimpleColumn.n_columns += 1 assert n_trays > 0, '{}: Number of tray must be greater than zero (specified {})'.format( self.name, n_trays) self.n_trays = n_trays assert (feed_tray >= 1) and (feed_tray <= self.n_trays-2), \ '{}: Feed tray number must be from 1 to {} inclusive (specified {}). No feed to the top or bottom trays for now' \ .format(self.name, self.n_trays-2, feed_tray) self.feed_tray = feed_tray self.feed_stream_liq = feed_stream_liq self.reflux = reflux self.vapor_reboil = vapor_reboil self.condensate = condensate self.bottoms = bottoms self.pressure = pressure self.n_vars = 0 self.n_eqns = 0 self.xvar = None self.eqns = None # figure out number of streams to be created as part of this column # for each tray, there are two streams leaving (one liquid, one vapor) # one liquid feed stream (comes from outside the column) # one stream that is a combination of the liquid feed stream and the liquid from the tray above the feed tray # create the streams associated with the column # tray liquid and vapor streams self.tray_liq_stream = [] for i_tray in range(self.n_trays): name = self.name + 'Tray' + str(i_tray) + 'Liquid' # self.tray_liq_stream.append(Stream(n_comps=N_COMPS, name=name)) self.tray_liq_stream.append( Stream(n_comps=self.feed_stream_liq.n_comps, name=name)) self.tray_vap_stream = [] for i_tray in range(self.n_trays): name = self.name + 'Tray' + str(i_tray) + 'Vapor' # self.tray_vap_stream.append(Stream(n_comps=N_COMPS, name=name)) self.tray_vap_stream.append( Stream(n_comps=self.feed_stream_liq.n_comps, name=name)) # create the mixed stream consisting of the feed stream and the liquid from the tray above the feed tray name = self.name + 'MixedLiquidFeed' # self.mixed_liq_feed = Stream(n_comps=N_COMPS, name=name) self.mixed_liq_feed = Stream(n_comps=self.feed_stream_liq.n_comps, name=name) self.unit_dict[name] = self.mixed_liq_feed # create the mixer needed to mix the liquid feed and the liquid from the tray above the feed tray name = self.name + 'FeedMixer' self.feed_mixer = Mixer(streams_in=[ self.feed_stream_liq, self.tray_liq_stream[feed_tray + 1] ], streams_out=[self.mixed_liq_feed], name=name) self.unit_dict[name] = self.feed_mixer # create trays self.trays = [] for i_tray in range(self.n_trays): name = self.name + 'Tray' + str(i_tray) if i_tray == self.feed_tray: self.trays.append( Tray( liq_stream_in=self.mixed_liq_feed, liq_stream_out=self.tray_liq_stream[i_tray], vap_stream_in=self.tray_vap_stream[i_tray - 1], vap_stream_out=self.tray_vap_stream[i_tray], tray_efficiency=1, # will be updated later pressure=self.pressure, name=name)) elif i_tray == 0: self.trays.append( Tray( liq_stream_in=self.tray_liq_stream[i_tray + 1], liq_stream_out=self.tray_liq_stream[i_tray], vap_stream_in=self.vapor_reboil, vap_stream_out=self.tray_vap_stream[i_tray], tray_efficiency=1, # will be updated later pressure=self.pressure, name=name)) elif i_tray == self.n_trays - 1: self.trays.append( Tray( liq_stream_in=self.reflux, liq_stream_out=self.tray_liq_stream[i_tray], vap_stream_in=self.tray_vap_stream[i_tray - 1], vap_stream_out=self.tray_vap_stream[i_tray], tray_efficiency=1, # will be updated later pressure=self.pressure, name=name)) else: self.trays.append( Tray( liq_stream_in=self.tray_liq_stream[i_tray + 1], liq_stream_out=self.tray_liq_stream[i_tray], vap_stream_in=self.tray_vap_stream[i_tray - 1], vap_stream_out=self.tray_vap_stream[i_tray], tray_efficiency=1, # will be updated later pressure=self.pressure, name=name)) self.update_tray_efficiency(tray_efficiency) for s in self.tray_liq_stream: self.unit_dict[s.name] = s for s in self.tray_vap_stream: self.unit_dict[s.name] = s for s in self.trays: self.unit_dict[s.name] = s name = self.name + 'CondensateConnector' self.condensate_connector = Connector(self.condensate, self.tray_vap_stream[n_trays - 1], name=name) self.unit_dict[name] = self.condensate_connector name = self.name + 'BottomsConnector' self.bottoms_connector = Connector(self.bottoms, self.tray_liq_stream[0], name=name) self.unit_dict[name] = self.bottoms_connector
class ExtendedCtrl(LooperCtrl): """Add screen connection and Mixer. Add looper commands""" __mixer: Mixer = Mixer() def __init__(self, scr_conn: Connection): LooperCtrl.__init__(self) self.__update_method: str = "" self.__description: str = "" self.__scr_conn: Connection = scr_conn def _redraw(self) -> None: """used by children to _redraw itself on screen""" if self.__update_method: method = getattr(self, self.__update_method) info = method() else: info = "" part = self.get_item_now() self.__scr_conn.send([ ConfigName.redraw, info, self.__description, part.length, self.idx, self._go_play.is_set(), self.get_stop_event().is_set() ]) def _prepare_redraw(self, update_method: str, description: str) -> None: self.__update_method = update_method self.__description = description if self._is_rec: self._is_rec = False part = self.get_item_now() loop = part.get_item_now() if loop.is_empty: loop.trim_buffer(self.idx, self.get_item_now().length) self._redraw() def _prepare_song(self) -> None: super()._prepare_song() self.items.append(SongPart(self)) self.items.append(SongPart(self)) self.items.append(SongPart(self)) self.items.append(SongPart(self)) # ========= change methods def _load_drum_type(self): self.drum.load_drum_type() self._redraw() def _change_mixer_in(self, change_by: int) -> None: out_vol: bool = False ExtendedCtrl.__mixer.change_volume(change_by, out_vol) self._redraw() def _change_mixer_out(self, change_by: int) -> None: out_vol: bool = True ExtendedCtrl.__mixer.change_volume(change_by, out_vol) self._redraw() def _change_drum_volume(self, change_by: int) -> None: self.drum.change_volume(change_by) self._redraw() def _change_drum_swing(self, change_by: int) -> None: self.drum.change_swing(change_by) self._redraw() def _change_drum(self) -> None: self.drum.play_break_now() def _change_song(self, *params) -> None: self._file_finder.iterate_dir(go_fwd=params[0] > 0) self._redraw() def _change_drum_type(self, *params) -> None: self.drum.change_drum_type(go_fwd=params[0] >= 0) self._redraw() def _change_drum_intensity(self, change_by: int) -> None: self.drum.change_intensity(change_by) # ================ show methods def _show_song_now(self) -> str: ff = self._file_finder return ff.get_item_now() def _show_song_next(self) -> str: ff = self._file_finder return ff.get_item_next() def _show_drum_type(self) -> str: return self.drum.show_drum_type() def _show_one_part(self) -> str: tmp = "" part = self.get_item_now() for k, loop in enumerate(part.items): tmp += loop.state_str(k == part.now, k == part.next) tmp += loop.info_str(USE_COLS) tmp += "\n" return tmp[:-1] def _show_all_parts(self) -> str: tmp = "" for k, part in enumerate(self.items): tmp += part.state_str(k == self.now, k == self.next) tmp += part.items[0].info_str( USE_COLS) if part.items_len else "-" * USE_COLS tmp += "\n" return tmp[:-1] def _show_drum_param(self) -> str: tmp = "vol:".ljust(STATE_COLS) + val_str(self.drum.volume, 0, 1, USE_COLS) + "\n" tmp += "swing:".ljust(STATE_COLS) + val_str(self.drum.swing, 0.5, 0.75, USE_COLS) return tmp @staticmethod def _show_mixer_volume() -> str: tmp = "out:".ljust(STATE_COLS) + val_str( ExtendedCtrl.__mixer.getvolume(out=True), 0, 100, USE_COLS) + "\n" tmp += "in:".ljust(STATE_COLS) + val_str( ExtendedCtrl.__mixer.getvolume(out=False), 0, 100, USE_COLS) return tmp @staticmethod def _show_version() -> str: return f"Version: {CURRENT_VERSION}" # ================ other methods def _fade_and_stop(self, *params): self._go_play.clear() seconds: int = params[0] ExtendedCtrl.__mixer.fade(seconds) self.stop_now() @staticmethod def _restart() -> None: ppid = os.getppid() run_os_cmd(["kill", "-9", str(ppid)]) @staticmethod def _check_updates() -> None: run_os_cmd(["git", "reset", "--hard"]) if 0 == run_os_cmd(["git", "pull", "--ff-only"]): ExtendedCtrl._restart() # ============ All song parts view and related commands def _clear_part_id(self, part_id: int) -> None: if part_id != self.now: self._is_rec = False part = self.items[part_id] self.next = self.now self._stop_never() if not part.is_empty: self.items[part_id] = SongPart(self) self._redraw() def _duplicate_part(self) -> None: part = self.get_item_now() if part.is_empty: return for x in self.items: if x.is_empty: x.items = copy.deepcopy(part.items) self._redraw() break def _undo_part(self) -> None: part = self.get_item_now() if part.items_len > 1: loop = part.items.pop() part.now = part.next = 0 if self._is_rec: self._is_rec = False else: part.backup.append(loop) self._redraw() def _redo_part(self) -> None: self._is_rec = False part = self.get_item_now() if len(part.backup) > 0: part.items.append(part.backup.pop()) self._redraw() # ================= One song part view and related commands def _change_loop(self, *params) -> None: if self._is_rec: return part = self.get_item_now() if params[0] == "prev": new_id = part.now - 1 new_id %= part.items_len part.now = new_id elif params[0] == "next": new_id = part.now + 1 new_id %= part.items_len part.now = new_id elif params[0] == "delete" and part.now != 0: part.items.pop(part.now) part.now = 0 elif params[0] == "silent" and part.now != 0: loop = self.get_item_now().get_item_now() loop.is_silent = not loop.is_silent elif params[0] == "reverse" and part.now != 0: loop = self.get_item_now().get_item_now() loop.is_reverse = not loop.is_reverse loop.is_silent = False elif params[0] == "move" and part.now != 0: loop = part.items.pop(part.now) part.items.append(loop) part.now = part.next = part.items_len - 1 self._redraw() def _undo_loop(self): self._is_rec = False part = self.get_item_now() if part.now == 0: self._undo_part() else: loop = part.get_item_now() if loop.is_empty: part.items.pop(part.now) part.now = part.next = 0 else: loop.undo() self._redraw() def _redo_loop(self): self._is_rec = False part = self.get_item_now() if part.now == 0: self._redo_part() else: loop = part.get_item_now() loop.redo() self._redraw()
class FMOperator(Oscillator): """A class to represent an FM operator""" def __init__( self, freq=440.0, level=1.0, phase=0.0, feedback=0, wave_type='sine', fm_type='DX', gate=Gate([0.0]), key_in=None ): Oscillator.__init__(self, key_in) self.freq = freq #frequency self.mixer = Mixer() #mixer to add modulators' outputs #sound generator if fm_type == 'LinearFM': self.generator = LinearFMGenerator( freq, level, phase, wave_type, self.mixer, key_in ) elif fm_type == 'DX': self.generator = DXGenerator( freq, level, phase, wave_type, self.mixer, key_in ) self.eg = ADSR(input=gate) #envelope generator #amplifier self.amp = Amplifier(input=self.generator, mod=self.eg) def add_modulator(self, mod, level=1.0): """Adds a modulator""" self.mixer.add_input(mod, level) def set_key_in(self, key_in): """Sets key input""" self.key_in = key_in self.generator.set_key_in(key_in) def set_eg_params(self, *args, **kwargs): """Sets parameters of the envelope""" self.eg.set_params(*args, **kwargs) def set_gate(self, gate): """Sets the gate input""" self.eg.set_input(gate) def set_keyboard(self, keyboard): """sets key and gate input from a keybord""" self.set_key_in(keyboard.key) self.set_gate(keyboard.gate) def output(self, t, **kwargs): """Returns the value of operators signal in time t""" return self.amp.output(t, **kwargs) def draw(self, ax, time=None, cycles=1, **kwargs): """ Draws the shape of the operators output signal along with its modulators and modulators' modulators etc. If 'time' is not provided, the shape will be drawn for 'cycles' cycles of operators carrier generator """ #draw the operators output signal Oscillator.draw(self, ax, time, cycles, **kwargs) #draw modulators' output signals if time is None: time = cycles / np.float64(self.freq) try: kwargs['alpha'] *= 0.5 except KeyError: kwargs['alpha'] = 0.5 self.mixer.draw(ax, time, **kwargs)
from mixer import Mixer, get_from_list, shuffled_ints, shuffled_decs if __name__ == "__main__": fn = get_from_list("lists/firstnames.txt") ln = get_from_list("lists/lastnames.txt") dates_f = get_from_list("lists/dates.txt") systems_f = get_from_list("lists/systems.txt") device_agents_f = get_from_list("lists/device_agents.txt") mixer = Mixer() mixer.set_delimiter('|') mixer.add_column(fn) mixer.add_column(ln) mixer.add_column(shuffled_ints(1, 5)) mixer.add_column(shuffled_ints(100, 250)) mixer.add_column(dates_f) mixer.add_column(systems_f) mixer.add_column(device_agents_f) mixer.add_column(dates_f) mixer.add_column(['\n']) print mixer.mix(number_of_records=100, with_incremental_id=False) with open('sample-data.txt', "w+") as f: f.writelines(["first_name|last_name|count_num|amount|start_date|name_2|name_3|date_1|empty_col\n"]) f.writelines(mixer.mix(number_of_records=100000, with_incremental_id=False))
class MixerTest(unittest.TestCase): def setUp(self): # pygame.display.init() self.mixer = Mixer(glob.glob("assets/sound/play_menu/*")) def tearDown(self): del self.mixer def test_volume(self): self.mixer.set_volume(0.34) self.assertEqual(self.mixer.get_volume(), 0.34) self.assertAlmostEqual(self.mixer.volume, pygame.mixer.music.get_volume(), 2) def test_stop(self): self.mixer.play_random() self.assertTrue(pygame.mixer.music.get_busy()) self.mixer.stop() self.assertFalse(pygame.mixer.music.get_busy()) def test_end_event(self): self.mixer.play_random() self.mixer.stop() self.assertTrue(pygame.event.get(SOUND_END))
class Player(AbstractPlayer): # ------------------------------------------------------------------------- # Initialization. # ------------------------------------------------------------------------- def __init__(self, display: Display): self.__mixer = Mixer() # precaution initial muting self.__mixer.mute() self.__stateFile = StateFile() self.__display = display self.__showInitInfo() self.__cdIsOver = False self.__mpv = MyMPV(self) self.__selectedSource = None self.__extConfig = self.__initExtConfig() # initial mute - arduino will send proper volumecommand # initial mute - arduino will send proper volumecommand # self.__switchToRadio() radioSource = RadioSource(display, self.__extConfig, self.__stateFile, self.__mixer, self) self.__cdSource = CDSource(display, self.__extConfig, self.__stateFile, self.__mixer, self) flashSource = FlashSource(display, self.__extConfig, self.__stateFile, self.__mixer, self) self.__sources = [radioSource, flashSource, self.__cdSource] self.__ringSources = cycle(self.__sources) self.switch() def __showInitInfo(self): try: nInfo = getNetworkInfo() if nInfo is not None: msg = self.__formatInitInfoMsg(nInfo) self.__display.showInfo(msg) # waiting to make the message readable time.sleep(1) else: self.__display.showError("Network not configured!") time.sleep(1) except Exception as e: logging.error(e, exc_info=True) raise e def __formatInitInfoMsg(self, nInfo: NetworkInfo) -> str: msg = "IF: " + nInfo.ifName msg += " " + "addr: " + nInfo.addr msg += " " + "ssid: " + str(nInfo.ssid) if nInfo.link: msg += " " + "link: " + str(nInfo.link) + "/70" return msg def handleButton(self, button: int): if button == B1 or button == B5: self.switch() else: if (self.__selectedSource is not None): self.__selectedSource.handleButton(button) def setVolume(self, volume: int): if (self.__selectedSource is not None): self.__selectedSource.setVolume(volume) def __initExtConfig(self) -> ExtConfig: try: return ExtConfig() except Exception as e: print(str(e)) self.__display.showError(str(e)) # allow for message propagation time.sleep(2) # finishing raise e def switch(self): nextAvailableSource = self.__findNextAvailableSource() if (nextAvailableSource is not None): self.__switchToSource(nextAvailableSource) def __findNextAvailableSource(self): for i in range(0, len(self.__sources)): source = next(self.__ringSources) if (source.isAvailable()): return source return None def __switchToSource(self, source): if self.__selectedSource is not None: self.__selectedSource.deactivate() self.__selectedSource = source source.activate() def close(self): self.__display.showInfo("The control software is shut down") self.__mixer.mute() self.__mpv.close() self.__display.close() self.__extConfig.close() def getMPV(self) -> MyMPV: return self.__mpv def restartMPV(self): if self.__mpv is not None: self.__mpv.close() self.__mpv = MyMPV(self) def getSelectedSource(self) -> Source: return self.__selectedSource def isPaused(self) -> bool: if self.__selectedSource is not None: return self.__selectedSource.isPaused() else: return True def isCDInserted(self) -> bool: return self.__cdSource.isCDInserted()
class PlayMenu(SpriteGroup): """Menu where the players are allowed to freely control their character(toon). The background image is chosen randomly as well as the currently playing music. """ def __init__(self, characters): """Initialize all attributes and music. utils -- SpriteGroup, contains background and timer players -- SpriteGroup, contains two characters skills -- SkillManager, contains the skills of both characters """ SpriteGroup.__init__(self) self.background = Background(random.choice(glob. glob("assets/fields/*"))) self.mana_time = 0 self.timer = Timer() self.timer.position = Vec2D(DEFAULT_SCREEN_SIZE[0] / 2, 30) self.mixer = Mixer(glob.glob("assets/sound/play_menu/*")) self.mixer.play_random() self.player1 = Character(1, characters[0], (0, 0)) self.player2 = Character(2, characters[1], DEFAULT_SCREEN_SIZE) self.skills = SkillManager(self.player1.skills, self.player2.skills) self.players = SpriteGroup(self.player1, self.player2) self.utils = SpriteGroup(self.background, self.timer) self.add(self.utils, self.players, self.skills) def update(self, time, input_list): """Consecutively update player1, player2, skill projectiles and check for collision after each update. Update enemy_position and direction attributes of each character, the background and the timer. Increase both players' mana points by a fixed rate(50 per second). PlayMenu.update(time, input_list): return None clock -- should be a pygame.time.Clock object """ self.player1.update(input_list) collide(self.player1, self.player2) collide(self.player1, self.player2.skills) self.player2.update(input_list) collide(self.player2, self.player1) collide(self.player2, self.player1.skills) self._update_enemy_positions() self.skills = SkillManager(self.player1.skills, self.player2.skills) self.skills.update(pygame.time.get_ticks()) collide(self.player2.skills, self.player1) collide(self.player1.skills, self.player2) self._boost_mana() self.utils.update(time) def _update_enemy_positions(self): """Update enemy_position and direction attributes of both characters according to their reciprocal positions. PlayMenu._update_enemy_positions(): return None Should not be used manually. """ self.player1.enemy_position = self.player2.rect self.player2.enemy_position = self.player1.rect if self.player1.position.x < self.player2.position.x: self.player1.direction = "Right" self.player2.direction = "Left" else: self.player1.direction = "Left" self.player2.direction = "Right" def _boost_mana(self): if self.timer.seconds - self.mana_time >= 1: self.player1.hud.mana.value += 50 if self.player1.hud.mana.value > self.player1.hud.mana.capacity: self.player1.hud.mana.value = self.player1.hud.mana.capacity self.player2.hud.mana.value += 50 if self.player2.hud.mana.value > self.player2.hud.mana.capacity: self.player2.hud.mana.value = self.player2.hud.mana.capacity self.mana_time = self.timer.seconds def draw(self, screen): """Draw all member sprites onto SCREEN surface. Scale SCREEN to the size of screen and draw SCREEN on screen. PlayMenu.draw(screen): return None """ super(PlayMenu, self).draw(SCREEN) screen.blit(pygame.transform.smoothscale(SCREEN, SCREEN_SIZE), (0, 0)) def stop_sound(self): """Stops any sound playback comming from both character members and the mixer. PlayMenu.stop_sound(): return None """ self.mixer.stop() self.player1.sound_effects.stop() self.player2.sound_effects.stop() def main(self, screen): """Run the play menu: process user input, update and draw all sprites onto the display. The fps is set to FPS. If the sound playback of the mixer ends a random sounds is played. PlayMenu.main(screen): return: EXIT if the display has been closed CHARACTER_MENU if the round has ended (a player died or the timer reached ROUND_TIME) """ clock = pygame.time.Clock() while True: clock.tick(FPS) pressed_keys = pygame.key.get_pressed() for event in pygame.event.get(): if event.type == pygame.QUIT: self.stop_sound() return EXIT elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.stop_sound() return CHARACTER_MENU elif event.type == SOUND_END: self.mixer.play_random() self.update(clock.get_time(), pressed_keys) self.draw(screen) pygame.display.flip() if (self.timer.time >= ROUND_TIME or self.player1.hud.get_health() == 0 or self.player2.hud.get_health() == 0): self.stop_sound() return CHARACTER_MENU
from color import Color from mixer import Mixer from time import Time import util import mask import font import sprite from locals import * time = Time() display = Display() image = Image() draw = Draw() transform = Transform() surfarray = Surfarray() mixer = Mixer() event = Event() mouse = Mouse() key = Key() init = lambda: None def quit(): canvas = display.get_canvas() canvas.stop() class error(RuntimeError): pass
from mixer import Mixer m = Mixer() m.init_all() m.calibrate_all() m.clean_gpio()
for handler in logging.root.handlers: logging.root.removeHandler(handler) logging.root.addHandler(customlog.MultiprocessingStreamHandler()) log = logging.getLogger(config.log_name) log.info("Starting %s...", config.app_name) track_queue = multiprocessing.Queue(1) log.info("Initializing read queue to hold %2.2f seconds of audio.", config.frontend_buffer) v2_queue = BufferedReadQueue(int(config.frontend_buffer / SECONDS_PER_FRAME)) info_queue = multiprocessing.Queue() mixer = Mixer(iqueue=track_queue, oqueues=(v2_queue.raw,), infoqueue=info_queue) mixer.start() if stream: import brain Hotswap(track_queue.put, brain).start() Hotswap(InfoHandler.add, info, 'generate', info_queue, first_frame).start() Hotswap(MonitorSocket.update, statistician, 'generate', get_listeners, mp3_queue=v2_queue).start() tornado.ioloop.PeriodicCallback( lambda: restart.check('restart.txt', started_at_timestamp,
def main(): sessions = AudioUtilities.GetAllSessions mixer = Mixer() # SysTrayIcon menu items menu_options = () # SysTrayIcon object systray = SysTrayIcon(None, "NK2Mixer", menu_options, on_quit=partial(exit_program, mixer)) # Start SysTray systray.start() # Map physical faders to Voicemeeter faders - mappings subject to personal preference with voicemeeter.remote('banana', 0.0005) as vmr: mixer.vb_map = { 4: vmr.inputs[3], 5: vmr.inputs[4], 6: vmr.inputs[1], 7: vmr.outputs[0] } for session in sessions(): if session.Process: print(session.Process.name) while mixer.running: # Receive midi message (non-blocking) msg = mixer.nk2_in.poll() # If no message exists, end current loop if not msg: continue # Check for select button press if msg.control in mixer.select_range and msg.value: group = mixer.groups[msg.control - mixer.select_fader_diff] # If program is not bound bound if not group.program: # Get active program name active_program = get_active_program() # Find audio session with matching name session = next( (s for s in sessions() if s.Process and s.Process.name() == active_program), None) # If audio session does not exist end current loop if not session: continue # Assign session to control group group.program = session # Turn on select button light mixer.enable_light(group.select) # If program is muted turn on mute button light if group.program.SimpleAudioVolume.GetMute(): mixer.enable_light(group.mute) print( f"{group.program.Process.name()} bound to fader {group.fader}" ) else: print( f"{group.program.Process.name()} unbound from fader {group.fader}" ) # Unassign session from fader group.program = None # Turn off select button light mixer.disable_light(group.select) # Turn off mute button light mixer.disable_light(group.mute) # Check for mute button press elif msg.control in mixer.mute_range and msg.value and mixer.groups[ msg.control - mixer.mute_fader_diff].program: group = mixer.groups[msg.control - mixer.mute_fader_diff] # Check if program is muted if group.program.SimpleAudioVolume.GetMute(): # Unmute program group.program.SimpleAudioVolume.SetMute(0, None) # Turn off mute button light mixer.disable_light(group.mute) print( f"{group.program.Process.name()} unmuted (fader {group.fader})" ) # If program is not muted else: # Mute program group.program.SimpleAudioVolume.SetMute(1, None) # Turn on mute button light mixer.enable_light(group.mute) print( f"{group.program.Process.name()} muted (fader {group.fader})" ) # Check for fader input elif msg.control in mixer.fader_range: group = mixer.groups[msg.control] # If fader does not have assigned program end current loop if not group.program: continue # Get volume control object from session volume = group.program._ctl.QueryInterface(ISimpleAudioVolume) # Convert midi value to percentage and set volume volume.SetMasterVolume(msg.value / 127, None) print( f"{group.program.Process.name()} set to {volume.GetMasterVolume() * 100}%" ) # Check for Voicemeeter fader input elif msg.control in mixer.vb_fader_range: # Map midi value (0-127) to VB appropriate gain value (-60-0) level = ((127 - msg.value) / 127) * -60 # Set VB fader gain mixer.vb_map[msg.control].gain = level print(f"fader {msg.control} (VoiceMeeter) gain set to {level}") elif msg.control in mixer.vb_mute_range and msg.value: fader = msg.control - mixer.mute_fader_diff control = mixer.vb_map[fader] # ISSUE: inconsistent mute/unmute if control.mute: # Unmute VB control control.mute = False # Turn off mute button light mixer.disable_light(msg.control) print(f"fader {fader} (VoiceMeeter) unmuted") else: # Mute FB control control.mute = True # Turn on mute button light mixer.enable_light(msg.control) print(f"fader {fader} (VoiceMeeter) muted") # After input is processed delete message to prevent unnecessary looping msg = None
def main(): global DISPLAYSURF, FPSCLOCK, FPS pygame.init() FPSCLOCK = pygame.time.Clock() FPS = 60 pygame.key.set_repeat(int(1000 / FPS)) global XMARGIN, YMARGIN, BOXSIZE width, height = pygame.display.Info().current_w, pygame.display.Info( ).current_h maxHeight = int(0.8 * height) maxWidth = int(1.5 * maxHeight) XMARGIN = YMARGIN = 0 BOXSIZE = 16 maxBoxSize = int((maxWidth / 15)) for scale in range(2, 5): if BOXSIZE * scale > maxBoxSize: break scale -= 1 scale = 3 BOXSIZE *= scale windowWidth = 15 * BOXSIZE windowHeight = 10 * BOXSIZE DISPLAYSURF = pygame.display.set_mode((windowWidth, windowHeight)) pygame.display.set_caption('Map Test') DISPLAYSURF.set_colorkey((255, 0, 255)) mixer = Mixer() player = Player(scale, party=[ get_pokemon(132, level=50), random_pokemon(level=50), random_pokemon(level=50) ]) # player = Player() playerSprite = pygame.sprite.Group() playerSprite.add(player) startX = player.get_position()[0] - 7 endX = startX + 15 startY = player.get_position()[1] - 5 endY = startY + 11 mainMap = load_map_square('main_map_full_test') mapSquare = mainMap.tiles mapImages, mapDecorations = mainMap.new_screen_images_array( player, tileSize=BOXSIZE) mixer.play_song(mainMap.tiles[player.x][player.y].group) global mapCoords mapCoords = [] for x in range(len(mapSquare)): column = [] for y in range(len(mapSquare)): column.append((x, y)) mapCoords.append(column) count = 0 maxCount = 4 running = True lastKeys = None change = True while running: offsetX, offsetY = 0, 0 count += 1 if count == maxCount: count = 0 position = player.get_position() move = (0, 0) columns = mapCoords[startX:endX] displayArea = [y[startY:endY] for y in columns] for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == KEYUP and event.key == K_ESCAPE): running = False elif event.type == KEYDOWN: if event.key == K_SPACE: interact(mainMap, player) elif event.key in [K_UP, K_w]: move = (0, -1) elif event.key in [K_DOWN, K_s]: move = (0, 1) elif event.key in [K_LEFT, K_a]: move = (-1, 0) elif event.key in [K_RIGHT, K_d]: move = (1, 0) elif event.type == KEYUP: if event.key == K_x: player.toggle_run() elif event.key == K_b: player.toggle_bike() change = True elif event.key == K_v and mainMap.surfable(player): player.toggle_surf() move = player.facing change = True else: pass if move != (0, 0): if mainMap.passable(player, move): change = True player.update(move) do_move(mapImages, playerSprite, mapDecorations, player, move) mapImages, mapDecorations = update_map(mainMap, mapImages, mapDecorations, player, move) elif mainMap.jumpable(player, move): change = True move = tuple_add(move, move) player.update(move) do_jump(mapImages, playerSprite, mapDecorations, player, move) mapImages, mapDecorations = update_map(mainMap, mapImages, mapDecorations, player, move) else: change = True player.turn(move) if mainMap.encounter_tile(player): # print('encounter') encounterPokemon = random_pokemon(level=50) WildBattle(DISPLAYSURF, mixer, player, encounterPokemon) # DISPLAYSURF.set_mode((windowWidth, windowHeight)) # keys = pygame.key.get_pressed() # if keys[K_SPACE]: # interact(mainMap, player) # elif keys[K_UP] or keys[K_w]: # move = (0, -1) # elif keys[K_DOWN] or keys[K_s]: # move = (0, 1) # elif keys[K_LEFT] or keys[K_a]: # move = (-1, 0) # elif keys[K_RIGHT] or keys[K_d]: # move = (1, 0) # if move != (0, 0): # if count == 0 and mainMap.passable(player, move): # change = True # offsetX = int(1*BOXSIZE/4) * move[0] # offsetY = int(1*BOXSIZE/4) * move[1] # elif count == 1 and mainMap.passable(player, move): # change = True # offsetX = int(2*BOXSIZE/4) * move[0] # offsetY = int(2*BOXSIZE/4) * move[1] # elif count == 2 and mainMap.passable(player, move): # change = True # offsetX = int(3*BOXSIZE/4) * move[0] # offsetY = int(3*BOXSIZE/4) * move[1] # elif count == 3 and mainMap.passable(player, move): # change = True # startX += move[0] # endX += move[0] # startY += move[1] # endY += move[1] # offsetX, offsetY = 0, 0 # player.update(move) # mapImages = update_map(mainMap, mapImages, player, move) # elif count == 3: # change = True # player.turn(move) if change: offsetX, offsetY = 0, 0 draw_screen(mapImages, playerSprite, mapDecorations, (offsetX, offsetY)) pygame.display.update() change = False # print(mainMap.tiles[player.x][player.y].group) if player.isBiking: mixer.play_song('Cycling') elif player.isSurfing: mixer.play_song('Surfing') else: mixer.play_song(mainMap.tiles[player.x][player.y].group) FPSCLOCK.tick(FPS)
op4 = FMOperator(6.9978*freq, .2) op5 = FMOperator(0.9997*freq, 1.4) op6 = FMOperator(0.9997*freq, .57) #set up algorithm #op1-->op2-->op3--\ #op4-->op5-->op6---\-->mixer-->speaker op3.add_modulator(op2) op2.add_modulator(op1) op6.add_modulator(op5) op5.add_modulator(op4) mixer = Mixer() mixer.add_input(op3) mixer.add_input(op6) mixer.set_level(0, 0.125) mixer.set_level(1, 0.125) #set up envelopes op1.set_eg_params(0.0, 0.11, 0.0, 0.05) op2.set_eg_params(0.0, 0.5, 0.3, 0.2) op3.set_eg_params(0.0, 0.5, 0.3, 0.4) op4.set_eg_params(0.0, 0.11, 0.0, 0.05) op5.set_eg_params(0.0, 0.7, 0.2, 0.2) op6.set_eg_params(0.0, 0.7, 0.2, 0.4)
name = channel.device.name_id fader = AudioFader(self.canvas, channel.get_gain, channel.set_gain, name) self.canvas.create_window(i * FADER_WIDTH, 0, anchor='nw', window=fader) class MixerWindow(Toplevel): def __init__(self, master, mixer): Toplevel.__init__(self, master, width=400) mixer_frame = MixerFrame(self, mixer) mixer_frame.grid(row=0, column=0, sticky='nwes') self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) if __name__ == '__main__': from mixer import Mixer from instruments import Drumset root = Tk() mixer = Mixer() for _ in range(10): mixer.add_device(Drumset()) mixer_frame = MixerWindow(root, mixer) root.mainloop() pass
# target_corners[7, :] = target_bbox[1] # return target_bbox, target_corners if __name__ == "__main__": # dataset = GRASSNewDataset('D:\\CMPT 764\\chairs_dataset',3) agg = Aggregator() #mixer = Mixer('Chair', 5, ['172', '182', '178', '517', '197']) #mixer = Mixer('Chair', 5, ['172', '173', '182', '178', '686']) #mixer = Mixer('Chair', 5, ['178', '348', '456', '504', '518']) #test_models: A = [197, 41103, 37574], B = [45075, 40015, 39696, 37658, 36193], C = [309, 1325, 3244, 36881, 37614, 40403, 42663, 37989, 3223, 41656] #mixer = Mixer('Chair', 3, ['197', '41103', '37574']) #mixer = Mixer('Chair', 5, ['45075', '40015', '39696', '37658', '36193']) mixer = Mixer('Chair', 10, [ '309', '1325', '3244', '36881', '37614', '40403', '42663', '37989', '3223', '41656' ]) #mixer.show_data_meshes() # extractor = RandomizedExtractor(dataset) mixer.show_data_meshes() for i in range(15): mixer.reset_target() print("Starting for model number ", i) mixer.mix_parts() renderMeshFromParts_new(mixer.get_target_mesh().parts, i) # for i in range(len(mixer.dataset)): # # mesh = mixer.dataset[i]