def shift(track, pause_duration): key = track[0].key shifted_track = Track() bar = Bar(key=key) bar.place_rest(pause_duration) input_note_containers = track.get_notes() for note in input_note_containers: placed = bar.place_notes(note[-1], note[1]) if not placed: beat_left = 1.0 - bar.current_beat beats_part_1 = beat_left beats_part_2 = 1 / note[1] - beats_part_1 if beats_part_1 != 0: duration_part_1 = 1 / beats_part_1 bar.place_notes(note[-1], duration_part_1) shifted_track.add_bar(copy.deepcopy(bar)) bar = Bar(key=key) duration_part_2 = 1 / beats_part_2 bar.place_notes(note[-1], duration_part_2) shifted_track.add_bar(copy.deepcopy(bar)) return shifted_track
def load_from_song(self, song): ''' Fills a mingus-composition object with the data of a Song object ''' if 'bar_length' in song.info: try: self.bar_length = song.info['bar_length'] except: print "You need to specify length of a Bar first before you can do this" for line in song.lines: track = Track() bar = Bar() for segment in line.segments: if segment.type == 'pause': int_val = None elif segment.type == 'note': int_val = segment.pitch n = Note().from_int(int_val + 48) note_length = float(self.bar_length) / segment.duration if not bar.place_notes(n, note_length): track.add_bar(bar) bar = Bar() bar.place_notes(n, note_length) track.add_bar(bar) self.composition.add_track(track) self.path = song.path self.song_name = song.reader.file_name[:-4]
async def on_start(self): self.agent.set("current_bar_no", 0) # inicializa "current_bar_no" en 0 # self.agent.set("tempo", 120) # self.agent.set("key", "C") self.agent.set("melody_track", Track()) self.agent.set("accompaniment_track", Track()) self.agent.set("current_melody_bar", Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE)) self.agent.set("current_accompaniment_bar", Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE))
def NewTrack(beats, count, withChromatics, with16): """ NewTrack(liczba_uderzeń_w_takcie, liczba_taktów, czy_z_chromatyką, czy_z_16) zwraca krotkę z trackiem i liczbą nut """ track = Track(Instrument()) rhythms = [] noOfNotes = 0 melodyCount = 0 for ii in range(count): rhythms.append(newBarRhythm(beats, with16)) noOfNotes += len(rhythms[ii]) if withChromatics: melody = newMelody(noOfNotes) else: melody = newMelodyWithoutChromatics(noOfNotes) for rhythm in rhythms: b = Bar("C", (beats, 4)) for note in rhythm: k = random.random() if k > pOfRests: b.place_notes(melody[melodyCount], 4 / note) else: b.place_notes(None, 4 / note) melodyCount += 1 track + b return (track, melodyCount)
def getPianoLoop(notes, preset): b = Bar() if preset == 'preset1': b.place_notes([notes[0], notes[1:]], 4) b.place_notes(notes[1:], 4) b.place_notes(notes[1:], 4) b.place_notes(notes[1:], 4) elif preset == 'preset2': b.place_notes([notes[0], notes[1:]], 8) b.place_notes(notes[2], 8) b.place_notes(notes[1:], 8) b.place_notes(notes[2], 8) b.place_notes(notes[1:], 8) b.place_notes(notes[2], 8) b.place_notes(notes[1:], 8) b.place_notes(notes[2], 8) elif preset == 'preset3': b.place_notes(notes[0], 4) b.place_notes(notes[2], 4) b.place_notes(changeOctave(notes[0], 1), 4) b.place_notes(changeOctave(notes[1:], 1), 4) elif preset == 'preset4': b.place_notes(notes[0], 4) b.place_notes(notes[1], 8) b.place_notes(notes[2], 4) b.place_notes(notes[3], 8) return b
def play(self, melody, chords, bpm, scores, bars, key, mode, modeToPass, tra, file, out_dir): t2 = Track() sh = progressions.to_chords(chords, key) for i in range(0, len(sh)): b = Bar(None, (4, 4)) if len(chords[i][0]) > 5: b.place_notes(None, 1) else: b.place_notes(NoteContainer(sh[i]), 1) t2 + b fluidsynth.pan(1, 25) fluidsynth.pan(2, 120) fluidsynth.main_volume(2, 50) fluidsynth.play_Tracks([melody, t2], [1, 2], bpm) # sleep(500000) button = Button(text='Clique para rearmonizar!', command=lambda: self.checkReharmonize( chords, scores, bars, key, mode, modeToPass, tra, bpm, file, out_dir), bg='brown', fg='white', font=('helvetica', 9, 'bold')) self.canvas1.create_window(200, 250, window=button)
async def run(self): cbn = self.agent.get("current_bar_no") if cbn < CFG.SONG_LENGTH: # falta sacar con modulo, de momento es un acorde por barra msg = await self.receive() if msg: if self.agent.get("chords_template").match(msg): if chords.determine_triad( getattr(chords, CFG.PROGRESSIONS[cbn])( CFG.SONG_KEY_SIGNATURE), True) == chords.determine_triad( msg.body.split(','), True): cab = self.agent.get("current_accompaniment_bar") cab.place_notes(msg.body.split(','), 1) # de momento es un acorde por barra at = self.agent.get("accompaniment_track") at.add_bar(cab) self.agent.set( "current_accompaniment_bar", Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE)) self.agent.set("accompaniment_track", at) self.set_next_state(S_RECEIVE_NOTE) else: self.set_next_state( S_RECEIVE_CHORD) # Continúa en el mismo estado else: self.set_next_state( S_RECEIVE_CHORD) # Continúa en el mismo estado else: self.set_next_state( S_RECEIVE_CHORD) # Continúa en el mismo estado else: self.set_next_state(S_PUBLISH_SONG)
def init_random_track(key, is_subject=True): notes = keys.get_notes(key) bar = Bar(key=key) while bar.current_beat < 1: # Randomize pitch and duration of each note. duration = 2**random.randint(1, 3) pitch = notes[random.randint(0, 6)] # If it is intened to be a subject, set the first note to the root. if bar.current_beat == 0 and is_subject == True: pitch = notes[0] # If the randomized duration doesn't fit in the bar, make it fit if 1 / duration > 1 - bar.current_beat: duration = 1 / (1 - bar.current_beat) # Place the new note in the bar bar.place_notes(pitch, duration) # Create a track to contain the randomized bar track = Track() track + bar # Return the track return track
def figGround(): # Purpose: Do a dictation of one instrument while other instruments are distracting in background. numnotes = setDuration() loopDictation = True while (loopDictation): randInstrument(1, set([ 0, 1, 2, 4, 6, 24, 25, 26, 27, 28, 29, 40, 41, 42, 56, 57, 60, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 78, 79, 80, 81, 82, 83, 85, 102, 103, 104, 105, 108, 109 ])) # Set lead/figure instr randInstrument(2, set([ 44, 45, 48, 49, 50, 51, 52, 53, 54, 55, 61, 62, 63, 86, 87, 88, 89, 90, 91, 92, 93 ])) # Set pad/ground instr randLeadNotes = [] for i in range(0, numnotes): randPitch = Note(12 * randint(3, 6) + randint(0, 12)) # randChord = randLeadNotes.append(randPitch) randBar = Bar() for n in randLeadNotes: randBar.place_notes(n, 4) playBeforeAnswer(randBar) print(randNotes) loopDictation = playAfterAnswer(randBar) print("\n")
def __init__(self, starting_note='C-3'): fluidsynth.init(path_to_instrument, audio_driver) self.starting_note = Note(starting_note) self.relative_major_scale = np.array([0, 2, 4, 5, 7, 9, 11]) self.scale = self.relative_major_scale + int(self.starting_note) self.note = Note(self.starting_note) self.bar = Bar() fluidsynth.play_Note(self.note)
def set_as_beat_strum(self): self.bars = [] for ch in self.chords: b = Bar(key=self.key) i = 0 while i < 4: b.place_notes(ch, 4) i += 1 self.add_bar(b)
def Bars_from_list(listb=[[0.0, 8.0, None],[0.125, 8.0, ['C-5']]]): ''' Helps TinyDB de-serialisation (load) Input list of (representations of) bars of the form [[position,duration,[note(s)]] , ...] Places these note events into Bar objects and returns as a list of Bars ''' #listb = [notev[0] if len(notev) == 1 else notev for notev in listb] # commented out as was repeating whole bars (notev = [whole bar note container nc]) listb = [nc if type(notev[0])!=float else notev for notev in listb for nc in notev] b = Bar() # we're instantiating Bars so I'm not sure why the outputs are sometimes type [list]..., cf fix_track_bar() bars = [b] for notev in listb: if notev != []: if bars[-1].place_notes(notev[2], notev[1]): pass else: bars.append(Bar()) bars[-1].place_notes(notev[2], notev[1]) return bars
def get_bar_from_chord(chord): chord = make_ascending(chord) # print chord b = Bar(meter=(len(chord) + 1, 4)) for n in chord: b.place_notes(n, 4) ## add quarter note b.place_notes(chord, 4) return b
def get_bar_from_triad(triad): assert len(triad) == 3 triad = make_ascending(triad) # print triad b = Bar() for n in triad: b.place_notes(n, 4) ## add quarter note b.place_notes(triad, 4) return b
def get_bar_from_interval(interval): assert len(interval) == 2 interval = make_ascending(interval) # print interval b = Bar() for n in interval: b.place_notes(n, 4) b.place_notes(interval, 2) return b
def fill_bars(self, arpeggio, note_duration=16, bars=1): generator = arpeggio.get_generator() while bars > 0: b = Bar() b.key = 'C' while not b.is_full(): b.place_notes(generator.next(), note_duration) self.track.add_bar(b) bars -= 1 return self.track
def fix_track_bar(bar): if type(bar) == list: # i.e. not Bar if bar == []: return [] if len(bar[0]) > 1: # len=3 if list [[a, b, NoteContainer]] b = Bar() b.place_notes(bar[0][2], bar[0][1]) bar = b else: # if list like [Bar] or [Bar, Bar] (hopefully no [Bar]x3's) return bar return [bar]
def sheets_from_peaks(peaks): """Generate and open the sheet music pdf that represents the notes contained in peaks.""" bass_range = Instrument() bass_range.set_range(['A-0', 'C-4']) bass_track = Track(bass_range) treble_range = Instrument() treble_range.set_range(['C-4', 'C-8']) treble_track = Track(treble_range) treble_track.add_bar(Bar()) bass_track.add_bar(Bar()) for time_slice in peaks: bass_chord, treble_chord = [], [] for note_index, note_value in enumerate(time_slice): if note_value: # add 9 to note_index to start at A-0 note = Note().from_int(note_index + 9) if bass_range.note_in_range(note): bass_chord.append(note) elif treble_range.note_in_range(note): treble_chord.append(note) if bass_chord == treble_chord == []: continue for chord, track in ((bass_chord, bass_track), (treble_chord, treble_track)): if track.bars[-1].is_full(): track.add_bar(Bar()) if chord: print chord track.bars[-1] + chord print track else: track.bars[-1].place_rest(4) print bass_track print treble_track merge_rests(treble_track, bass_track) save_and_print(treble_track, bass_track)
def easy_bar(notes, durations=None): _default_note_duration = 4 if not durations and notes is not None: durations = [_default_note_duration] * len(notes) # setup Bar object bar = Bar() if (isinstance(notes, NoteContainer) or isinstance(notes, Note) or notes is None): bar.place_notes(notes, _default_note_duration) elif notes is None: bar.place_notes(notes, _default_note_duration) else: for x, d in zip(notes, durations): bar.place_notes(x, d) return bar
def write_mingus(self, outfile): notes = list(self.timeseries['Notes']) t = Track() for n in range(len(notes)): if n % 4 == 0: b = Bar(self.key, (4, 4)) if notes[n] != 'Z': b + notes[n] else: b + None if (n + 1) % 4 == 0: t + b self.composition + t self.track = t lily_composition = LilyPond.from_Composition(self.composition) print lily_composition LilyPond.to_pdf(lily_composition, outfile)
def createMingusComposition(intermed, timesig, bIsTreble, bSharps): comp = Composition() comp.set_title('Trilled Results') comp.set_author('Author') if bIsTreble: ins = TrebleInstrument('') else: ins = BassInstrument('') track = Track(ins) track.name = 'Part 1' comp.add_track(track) assert len(timesig) == 2 and isinstance(timesig[0], int) and isinstance( timesig[1], int) firstbar = Bar(meter=timesig) track.add_bar(firstbar) mapDurs = { int(intermed.baseDivisions * 4): 1.0, #whole note, int(intermed.baseDivisions * 2): 2.0, #half note int(intermed.baseDivisions * 1): 4.0, #qtr note, and so on int(intermed.baseDivisions * 0.5): 8.0, int(intermed.baseDivisions * 0.25): 16.0, int(intermed.baseDivisions * 0.125): 32.0, int(intermed.baseDivisions * 0.0625): 64.0, } for note in intermed.noteList: if note.pitch == 0 or note.pitch == (0, ): # a rest thepitches = tuple() else: # a note thepitches = [] for pitch in note.pitch: pname, poctave = music_util.noteToName(pitch, bSharps) thepitches.append(pname + '-' + str(poctave)) dur = note.end - note.start if dur not in mapDurs: raise NotesinterpretException('Unknown duration:' + str(dur)) notecontainer = NoteContainer(thepitches) notecontainer.tied = note.isTied bFit = track.add_notes(notecontainer, mapDurs[dur]) assert bFit #note that, naturally, will enforce having correct measure lines, since going across barline throughs exception return comp
def generate_bar(difficulty: float): some_bar = Bar('C', (4, 4)) values = [ value.whole, value.half, value.quarter, value.dots(value.half), value.eighth, value.dots(value.quarter), value.sixteenth, value.dots(value.eighth), value.quarter, value.dots(value.quarter) ] actual_values = [] pitches = [ Note("A", 3), Note("B", 3), Note("C", 4), Note("D", 4), Note("E", 4), Note("F", 4), Note("G", 4), Note("A", 4), Note("B", 4), Note("C", 5), Note("D", 5), Note("E", 5), Note("F", 5), Note("G", 5), Note("A", 5), Note("B", 5), Note("C", 6) ] if difficulty >= 10: actual_values = values else: index = math.ceil(difficulty) actual_values = values[0:index] while some_bar.place_notes(choice(pitches), choice(actual_values)): pass if not some_bar.is_full(): some_bar.place_notes(choice(pitches), some_bar.value_left()) return some_bar
def split_bar(bar, split_point): current_pos = 0 bar_l = Bar() if 1/bar[0][1] > split_point: # if the first event crosses the split point (e.g. a conjoined rest) bar_l.place_notes(bar[0][2], 1/split_point) current_pos += split_point bar = [[bar[0][0], 1/(1/bar[0][1]-split_point), bar[0][2]]] + bar[1:] while current_pos < split_point: bar_l.place_notes(bar[0][2], bar[0][1]) current_pos += 1/bar[0][1] bar = bar[1:] bar_r = bar bar_r = [fix_track_bar([b])[0] for b in bar_r] return bar_l, bar_r
def getGuitarLoop(notes, preset): b = Bar() if preset == 'preset1': b.place_notes(notes[0], 4) b.place_notes(notes[2], 4) b.place_notes([changeOctave(notes[0], 1), changeOctave(notes[1], 1)], 4) b.place_notes(notes[2], 4) if preset == 'preset2': b.place_notes(notes[0], 8) b.place_notes(notes[2], 8) b.place_notes(changeOctave(notes[0], 1), 8) b.place_notes(notes[2], 8) b.place_notes(changeOctave(notes[1], 1), 8) b.place_notes(notes[2], 8) b.place_notes(changeOctave(notes[0], 1), 8) b.place_notes(notes[2], 8) return b
def reverse(track, key='C'): # Copy value of reference to aviod problems with overwriting input_track = copy.deepcopy(track) #empty track to write to later reversed_track = Track() b = Bar(key) reversed_track.add_bar(b) #create a reversed list of notes from input track input_notes = input_track.get_notes() reversed_notes = reversed(list(input_notes)) #Add notes to reversed_track for note in reversed_notes: reversed_track.add_notes(note[-1], duration=note[1]) # Return reversed track return reversed_track
def set_as_split_chords(self): self.bars = [] noted_chords = map(lambda x: assign_octaves(x, self.octave), self.chords) for ch in noted_chords: b = Bar(key=self.key) if len(ch) == 3: b.place_notes(ch[0], 4) b.place_notes(ch[2], 4) b.place_notes(ch[1], 4) b.place_notes(ch[2], 4) elif len(ch) == 4: b.place_notes(ch[0], 4) b.place_notes(ch[2], 4) b.place_notes(ch[1], 4) b.place_notes(ch[3], 4) else: b.place_notes(ch, 1) self.add_bar(b)
def notes_durations_to_track(_notes, durations=None): ''' params: - _notes: list of list of Notes [['G','B','D','F'], ['C','E','G','B']] - durations: Durations should be a list of integers e.g. [2,2,1] will give | chord 1 chord 2 | chord 3 | TO-DO: - mingus durations are limited to =< 1 bar; we want to be able to parse a duration of '0.5' (because in mingus '4'=crotchet i.e. num subdivs) to refer to 2 bars (just use 1/d) ''' if durations is None: durations = [1] * len(_notes) t = Track() for i, _note in enumerate(_notes): b = Bar() b.place_notes(_note, durations[i]) t.add_bar(b) return t
async def run(self): cbn = self.agent.get("current_bar_no") msg = await self.receive() if msg: if self.agent.get("notes_template").match(msg): if Note(msg.body.split(",")[0]).name in getattr( chords, CFG.PROGRESSIONS[cbn])(CFG.SONG_KEY_SIGNATURE): cmb = self.agent.get("current_melody_bar") if cmb.current_beat + 1 / float( msg.body.split(",")[1]) <= cmb.length: cmb.place_notes( msg.body.split(",")[0], int(msg.body.split(",") [1])) # de momento 4 notas por barra if cmb.current_beat == cmb.length: # chechar si llena, entonces agregar a melody_track mt = self.agent.get("melody_track") mt.add_bar(cmb) self.agent.set("melody_track", mt) self.agent.set( "current_melody_bar", Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE)) self.agent.set("current_bar_no", cbn + 1) print( "{}: {}/{}".format(self.agent.name, cbn + 1, CFG.SONG_LENGTH) ) # falta sacar con modulo, de momento es un acorde por barra self.set_next_state(S_RECEIVE_CHORD) else: self.agent.set("current_melody_bar", cmb) self.set_next_state(S_RECEIVE_NOTE) else: self.set_next_state( S_RECEIVE_NOTE) # Continúa en el mismo estado else: self.set_next_state( S_RECEIVE_NOTE) # Continúa en el mismo estado else: self.set_next_state( S_RECEIVE_NOTE) # Continúa en el mismo estado else: self.set_next_state(S_RECEIVE_NOTE) # Continúa en el mismo estado
def change_speed(track, factor, key, up=True): changed_track = Track() #if factor is 0 we return an empty track if (factor != 0.0): input_track = copy.deepcopy(track) input_notes = input_track.get_notes() b = Bar(key=key) changed_track.add_bar(b) #if we want to speed up (notespeed *= factor) if up: for note in input_notes: changed_track.add_notes(note[-1], int(note[1] * factor)) #if we want to slow down (notespeed *= (1/factor)) else: for note in input_notes: changed_track.add_notes(note[-1], int(note[1] / factor)) return changed_track
def setup_tracks(midi_file_out=None): from tracks import melodies, cantus_firmus, key, meter, species, author # Create a composition, and add the vocal tracks to it. composition = Composition() composition.set_title('Counterpoint Exercise', '') composition.set_author(author, '') # Set up our vocal 'tracks' with the notes, key, meter defined in tracks.py tracks = {} for voice in [Soprano, Alto, Tenor, Bass]: if len(melodies[voice.name]): tracks[voice.name] = Track(instrument=voice()) tracks[voice.name].add_bar(Bar(key=key, meter=meter)) tracks[voice.name].name = voice.name for note in melodies[voice.name]: tracks[voice.name].add_notes(*note) composition.add_track(tracks[voice.name]) if midi_file_out is not None: # Save the midi file! write_Composition(midi_file_out, composition, verbose=True) return composition, [], species