Beispiel #1
1
    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]
Beispiel #2
0
    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]
Beispiel #3
0
    def generate(self):
        
        
        nr_of_bars = random.randint(3,10)	
        diatonic =  self.get_major_scale("A")  # example : ['C', 'Db', 'Eb', 'F', 'G', 'Ab', 'Bb']
        
         
        
        arrangement = self.basic_song_structure() # arragement.structure and arragement.parts are used

        generated_parts = []
        for i in range(0,len(arrangement["parts"])):
            proggresion = self.random_progression(diatonic,"-2")
            rhythm = self.gen_rhythm(proggresion)

            generated_bar_with_rhythm = self.gen_with_rhythm(proggresion,rhythm,diatonic)

            print "proggresiion ="+ str(proggresion)
            print "rhythm= " + str(rhythm)
            

            
            generated_bar = self.gen_simple(diatonic,4,proggresion)
            generated_parts.append(generated_bar_with_rhythm)
        
        song = Track()
        for i in arrangement["structure"]:
            song.add_bar(generated_parts[i])

        self.gen_rhythm(proggresion)
        return song   
Beispiel #4
0
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 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
Beispiel #6
0
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
Beispiel #7
0
def play_smart_solo_over_chords(chord_list):
	fluidsynth.set_instrument(13, 45)
	fluidsynth.set_instrument(10, 108)

	fluidsynth.main_volume(13, 75)
	fluidsynth.main_volume(10, 100)
	
	solo = Track()

	bars = generate_solo(chord_list)
	for i in range(len(bars)):
		chord = NoteContainer(chords.from_shorthand(chord_list[i]))
		bar = bars[i]
		fluidsynth.play_NoteContainer(chord, 13)
		fluidsynth.play_Bar(bar, 10)
		fluidsynth.stop_NoteContainer(chord, 13)
		solo.add_bar(bar)
	return solo
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
Beispiel #9
0
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
Beispiel #10
0
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)
Beispiel #11
0
class TrackBuilder(object):
    def __init__(self):
        self.track = Track()

    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 from_dsl(self, string):
        plan, bpm, loop = dsl.parse_string(string)
        for x in range(loop):
            for arpeggio, duration in plan:
                self.fill_bars(arpeggio, duration[0], duration[1])
        return self.track, bpm
Beispiel #12
0
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
Beispiel #13
0
class TrackBuilder(object):
    def __init__(self):
        self.track = Track()

    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 from_dsl(self, string):
        plan, bpm, loop = dsl.parse_string(string)
        for x in range(loop):
            for arpeggio, duration in plan:
                self.fill_bars(arpeggio, duration[0], duration[1])
        return self.track, bpm
Beispiel #14
0
def main(config_path):
    pickle_in = open("saved_winners.pickle", "rb")
    genomes = pickle.load(pickle_in)
    pickle_in.close()

    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_path)

    for x, genome in enumerate(genomes):
        trainer.eval_fitness([(1, genome)], config)

        fitness = genome.fitness

        float_name = fitness * 1000

        int_name = int(float_name)

        name = str(int_name)

        os.mkdir(name)

        for i in range(15):
            song = trainer.generate_song(x + 1)

            track = Track()

            for bar in song:
                track.add_bar(bar)

            xml = musicxml.from_Track(track)

            path = name + "\\" + str(i) + ".musicxml"
            xml_file = open(path, "w")

            xml_file.write(
                '<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE score-partwise PUBLIC "-//Recordare//DTD MusicXML 2.0 Partwise//EN"\n  "http://www.musicxml.org/dtds/partwise.dtd">\n'
                + xml)
Beispiel #15
0
# that's stupid
# http://www.youtube.com/watch?v=5pidokakU4I

prg = [tr("C"), tr("G"), tr("A"), tr("F")]

bars = []

for chord in prg:
    b = Bar()
    b.place_notes(chord, 4)

    bars.append(b)

t = Track()


for b in bars:
    t.add_bar(b)
    

instrs = list(enumerate(MidiInstrument.names))
shuffle(instrs)

for i, name in instrs:
    print i, name
    fluidsynth.set_instrument(1, i)
        
    fluidsynth.play_Track(t)


Beispiel #16
0
def init_preset_track(num):
    track = Track()
    if num == 1:  #C-chord
        track.add_notes(None)
        track.add_notes(None)
        nc = NoteContainer(["C", "E"])
        track.add_notes(nc)
        track + "E-5"
        track + "A-3"
        track.add_notes(None)
        track + "C-5"
        track + "E-5"
        nc2 = NoteContainer(["F", "G"])
        track.add_notes(nc2)
        track + "G-5"
        track + "C-6"
    if num == 2:
        track + "E"
        track + "D"
        track + "E"
        track + "A-2"
        track + "C"
        track + "D"
        track + "E"
        track + "F-5"
        track + "D"
        track + "E"
        track + "E-5"
    if num == 3:
        test_scale = scales.Major("C")
        for i in range(7):
            track + test_scale[i]
    if num == 4 or num == 'blinka':
        bar = Bar()
        bar.place_notes('C-4', 8)
        bar.place_notes('C-4', 8)
        bar.place_notes('G-4', 8)
        bar.place_notes('G-4', 8)
        bar.place_notes('A-4', 8)
        bar.place_notes('A-4', 8)
        bar.place_notes('G-4', 4)
        track.add_bar(bar)

    if num == "nokia":  #scale A
        track.add_notes('E-4', 16)
        track.add_notes('D-4', 16)
        track.add_notes('F#-3', 8)
        track.add_notes('G#-3', 8)
        track.add_notes('C#-4', 16)
        track.add_notes('B-3', 16)

        track.add_notes('D-3', 8)
        track.add_notes('E-3', 8)
        track.add_notes('B-3', 16)
        track.add_notes('A-3', 16)
        track.add_notes('A-3', 8)

    if num == "windows":  #scale C#
        track.add_notes('D#-5', 4)
        track.add_notes('A#-4', 8)
        track.add_notes('G#-4', 4)
        track.add_notes('D#-5', 8)
        track.add_notes(['A#-3', 'D#-4', 'A#-4'], 4)

    if num == "brick":  #scale C
        track.add_notes('E-4', 4)
        track.add_notes('B-3', 8)
        track.add_notes('C-4', 8)
        track.add_notes('D-4', 4)
        track.add_notes('C-4', 8)
        track.add_notes('B-3', 8)

    if num == "panther":  #Scale E
        track.add_notes('D#-4', 8)
        track.add_notes('E-4', 8 / 3)
        track.add_notes('F#-4', 8)
        track.add_notes('G-4', 8 / 3)
    return track
Beispiel #17
0
def generate_midi(instrument,
                  key,
                  chord_progression,
                  pad,
                  octave=None,
                  applause=False):
    composition = Composition()

    how_many_bars = 16

    # Make all these configurable
    # Or make them all random from a range
    track = Track(instrument, channel=1)

    drone_track = track_creator(pad, channel=2)
    # drone_track = track_creator("Pad4 (choir)", channel=2)

    # It's one of the few pitched drums
    timpani_track = track_creator("Timpani", channel=3)

    applause_track = track_creator("Applause", channel=4)

    bar = Bar(key, (4, 4))
    nc = NoteContainer("C", octave=2)
    bar.place_notes(nc, 1)
    applause_track.add_bar(bar)

    for _ in range(how_many_bars):

        # Can we get an index
        # We can with enumerate, but why do we want it
        for chord in chord_progression:
            # The Chord Progression

            bar = Bar(key, (4, 4))
            if not octave:
                octave = INSTRUMENT_OCTAVE.get(instrument.name, 4)

            for length in random.sample(CHORD_RHYTHMS, 1)[0]:
                some_notes = random.sample(chord,
                                           random.randint(1, len(chord)))
                nc = NoteContainer(some_notes, octave=int(octave))
                bar.place_notes(nc, length)
            track.add_bar(bar)

            drone_bar = Bar(key, (4, 4))
            nc = NoteContainer(chord[0], octave=2)
            drone_bar.place_notes(nc, 1)
            drone_track.add_bar(drone_bar)

            timpani_bar = Bar(key, (4, 4))
            nc = NoteContainer(key, octave=2)
            for length in [4, 4, 4, 4]:
                timpani_bar.place_notes(nc, length)
            timpani_track.add_bar(timpani_bar)

    composition.add_track(timpani_track, channel=5)
    composition.add_track(drone_track)
    composition.add_track(track)

    # Do we want to add the channel when adding or creating the track?
    if applause:
        composition.add_track(applause_track)

    instrument_name = MidiInstrument.names[instrument.instrument_nr]
    write_Composition(midi_file_name(instrument_name), composition, bpm=120)
Beispiel #18
0
	def __init__(self, name):
		self.name = name
		Instrument.__init__(self)

comp = Composition()
comp.set_title('The Mingus')
comp.set_author('Ben')

ins = TrebleInstrument('kazoo')

track = Track(ins)
track.name = 'WWW' #instead of 'untitled'
comp.add_track(track)

firstbar = Bar(meter=(3,4))
track.add_bar(firstbar)
print track.add_notes(['C-5'], 4.0)
print track.add_notes(['E-5'], 2.0)

print track.add_notes(['C-4','D-4'], 8.0)
print track.add_notes(['C-4','D-4','F-4'], 8.0)
print track.add_notes([], 8.0) #treated as rest?
print track.add_notes(['C-4','D-4'], 8.0)
print track.add_notes(['C-4','D-4'], 8.0)
print track.add_notes(['C-4','D-4'], 8.0)
print track.add_notes(['C-4','D-4'], 24.0)
print track.add_notes(['C-4','D-4'], 24.0)
print track.add_notes(['C-4','D-4'], 24.0)
print track.add_notes(['C-4','D-4'], 8.0)

s = MusicXML.from_Composition(comp)
    def gen_midi(self, tracks_data):
        c = Composition()

        all_tracks = tracks_data["tracks_data"]
        curr_track = 0;

        for track_data in all_tracks:
            #TODO: set author, title, more specific instrument (that has a
            #range set

            data_max = max(track_data["note_data"])
            data_min = min(track_data["note_data"])

            data_dur_max = max(track_data["dur_data"])
            data_dur_min = min(track_data["dur_data"])

            data_range = data_max - data_min

            ####DURATIONS####
            midi_durs = [self.map_range(0, len(self.mapping_dur_vals) - 1,
                                   data_dur_min, data_dur_max, x, "dur")
                         for x in track_data["dur_data"]]
            midi_durs = [self.mapping_dur_vals[int(x)] for x in midi_durs]
            print "midi_durs: "
            print midi_durs

            ####PITCHES####
            midi_vals = [self.map_range(0, len(self.overall_mapping_vals) - 1,
                                   data_min, data_max, x, "notes")
                         for x in track_data["note_data"]]
            midi_vals = [self.overall_mapping_vals[int(x)] for x in midi_vals]

            print "midi_pitches: "
            print midi_vals

            for instr in self.instrs:
                t = Track()
                b = Bar()
                for index, midi_val in enumerate(midi_vals):
                    print "-----------------"
                    print "space left in bar"
                    print b.space_left()
                    if midi_val in instr["mapping_vals"]:
                        print "inserting NON-REST NOTE"
                        print "inserting NON-REST NOTE"
                        val_to_insert = Note().from_int(int(midi_val))
			print "DONE INSERTING NON-REST NOTE"
                    else:
                        print "INSERTING REST"
                        val_to_insert = None #insert rest instead

                    print "ABOUT TO INSERT"
                    dur_to_insert_1 = 1.0/((1.0/float(midi_durs[index])) * 0.99)
                    dur_to_insert_2 = 1.0/((1.0/float(midi_durs[index])) * 0.01)
                    b, insert_result_1 = self.insert_into_bar(curr_track, b, val_to_insert,
                                                         dur_to_insert_1)
                    print "trying to insert note..."
                    print insert_result_1
                    print "midi note DURATION is: "
                    print midi_durs[index]

                    if insert_result_1:
                         b, insert_result_2 = self.insert_into_bar(curr_track, b, None,
                                                         dur_to_insert_2)
                         print "trying to insert note..."
                         print insert_result_2
                         print "midi note DURATION is: "
                         print midi_durs[index]

                    if not insert_result_1:
                        if b.space_left() == 0.0:
                            print "hit edge case!!!!"
                            t.add_bar(b)
                            b = Bar()
                            b, insert_result = self.insert_into_bar(curr_track,
                                                                    b, val_to_insert, dur_to_insert_1)
                            b, insert_result = self.insert_into_bar(curr_track,
                                                                    b, None, dur_to_insert_2)
                            print "bar is now (after edge case): "
                            print b
                            continue

                        space_p = b.space_left()
                        space = 1.0/space_p
                        print "space percentage left: "
                        print space_p
                        print "note space left: "
                        print space

                        note_remainder = value.subtract(midi_durs[index], space)
                        print "note duration: "
                        print midi_durs[index]
                        print "note remainder: "
                        print note_remainder

                        print "bar before INSERTING PART 1 OF TIE: "
                        print b
                        dur_to_insert_1_space = 1.0/((1.0/float(space)) * 0.99)
                        dur_to_insert_2_space = 1.0/((1.0/float(space)) * 0.01)
                        if space <= 16.0:
                             print "NOTE IS LARGER THAN 16 NOTE"
                             b, insert_result = self.insert_into_bar(curr_track, b, val_to_insert, dur_to_insert_1_space)
                             b, insert_result = self.insert_into_bar(curr_track, b, None, 1.0/b.space_left())
                        else:
                             print "NOTE IS *NOT* LARGER THAN 16 NOTE"
                             b, insert_result = self.insert_into_bar(curr_track, b, None, space)
                        print "bar AFTER: "
                        print b
                        print "inserting part one of tie result: "
                        print insert_result
                        print "is bar full??? (IT SHOULD BE)"
                        print b.is_full()
                        t.add_bar(b)

                        b = Bar()
                        b, insert_result = self.insert_into_bar(curr_track, b, None, note_remainder)
                        print "inserting part TWO of tie result: "
                        print insert_result
                        print "bar after inserting remaining piece: "
                        print b

                    print "BAR IS NOW"
                    print b
                    #end for

                #add last bar
                if b.space_left() == 0.0:
                    t.add_bar(b)
                else:
                    #need to fill remaining space with rest
                    space_p = b.space_left()
                    space = 1.0/space_p
                    #b, insert_result = self.insert_into_bar(curr_track, b,
                    #                                        Note(None), space)
                    print "result for filling rest of last bar with rest: "
                    print insert_result
                    print "is bar full after adding rest to end of last bar??? (IT SHOULD BE)"
                    print b.is_full()
                    print "bar WITH REST is now: "
                    print b
                    t.add_bar(b)
                logger.debug("Track: ")
                logger.debug(t)
                #at very end of loop add track to composition
                c.add_track(t)

            curr_track += 1

        #write_Composition("midi_success.mid", c);
        return self.gen_midi_data(c)
Beispiel #20
0
            leadBar.place_notes(n, lastNoteLength)
        else:
            # add a rest
            leadBar.place_rest(choice(noteLengths))

    lead.append(leadBar)

    for note in container:
        note = note.octave_down()

    noteLengths = [1]
    bar = Bar(key, meter)
    bar.place_notes(container, choice(noteLengths))
    comp.append(bar)

track = Track()
for bar in comp:
    track.add_bar(bar)

leadTrack = Track()
for bar in lead:
    leadTrack.add_bar(bar)

composition = Composition()
composition.add_track(track)
# composition.add_track(leadTrack)

MidiFile.write_Composition("musgen.mid", composition)
MidiFile.write_Track("musgenLead.mid", leadTrack)
Beispiel #21
0
def compose(primary_pc_sets, rhythm_cycles, ensemble, meter, bpm, stability, repeat_chance, repeat_attempts, repeat_loops, repetitions, filename = 'output.mid'):
	"""
	Generates a post-tonal composition and resultant midi file
	using the given materials (function arguments) in conjunction
	with stochastic processes.
	Takes a list of PcSets, a list of Rythm_cycles, a list of Instruments,
	an integer tuple for meter (time signature), an integer for bpm
	(tempo), a floats for stability and repeat_chance, integers for
	repeat_loops and repetitions, and a string for output filename.
	"""
	
	for pc_set in primary_pc_sets:
		assert isinstance(pc_set, PcSet)
	for rhythm_cycle in rhythm_cycles:
		assert isinstance(rhythm_cycle, Rhythm_cycle)
	for instrument in ensemble:
		assert isinstance(instrument, Instrument)
	assert isinstance(meter, tuple)
	assert isinstance(bpm, int)
	assert isinstance(stability, int) or isinstance(stability, float)
	assert stability >= 0 and stability <= 100
	assert isinstance(repeat_chance, int) or isinstance(repeat_chance, float)
	assert repeat_chance >= 0 and repeat_chance <= 100
	assert isinstance(repeat_attempts, int)
	assert repeat_attempts in range(0, 101)
	assert isinstance(repeat_loops, int)
	assert repeat_loops in range(0, 101)
	assert isinstance(repetitions, int)
	assert repetitions in range(0, 101)
	assert isinstance(filename, str)

	# print parameters:
	print "\nBasic Parameters:\n"
	print "Meter: " + str(meter)
	print "BPM: " + str(bpm)
	print "Repeat chance:" + str(repeat_chance)
	print "Repeat attempts:" + str(repeat_attempts)
	print "Repeat loops:" + str(repeat_loops)
	print "Repetitions: " + str(repetitions)
	print "Output Destination: " + filename

	print "\nPrimary Pitch-Class Sets:"
	for index, item in enumerate(primary_pc_sets):
		interval_vector = item.ivec()
		common_tone_vector = ctvec(item)
		print "\n#" + str(index+1) + ":"
		print "Pitch-Class Set: " + str(item)
		print "Interval Vector: " + str(interval_vector)
		print "Common-Tone Vector: " + str(common_tone_vector)

	print "\nRhythm Cycles:"  
	for index, rhythm in enumerate(rhythm_cycles):
		print "\n#" + str(index+1) + ":"
		rhythm_cycles[-1].display()

	# compose pc_set_progression sections:
	pc_set_progression = list()
	section_length = list()

	# section 1:
	for index in range(len(primary_pc_sets)):
		for primary_pc_set in primary_pc_sets[0:index+1]:
			spectrum = transposition_spectrum(primary_pc_set)
			contrast = index
			if contrast not in range(len(spectrum)):
				contrast = len(spectrum)-1 
			pc_set_progression.extend(neighbor_by_contrast(primary_pc_set, contrast))
	section_length.append(len(pc_set_progression))

	# section 2:
	for index, primary_pc_set in enumerate(primary_pc_sets[0:-1]):
		spectrum = transposition_spectrum(primary_pc_set)
		contrast = index
		if contrast not in range(len(spectrum)):
			contrast = len(spectrum)-1
		pc_set_progression.extend(palindrome_successive_neighbor_by_contrast(primary_pc_set, contrast, len(primary_pc_sets[0:-1])-index))
	section_length.append(len(pc_set_progression))

	# section 3:
	primary_pc_set = primary_pc_sets[-1]
	spectrum = transposition_spectrum(primary_pc_set)
	contrast = len(spectrum)-1
	pc_set_progression.extend(cadential_progressive_successive_neighbor(primary_pc_set))
	section_length.append(len(pc_set_progression))

	# section 4:
	for index, primary_pc_set in enumerate(reversed(primary_pc_sets)):
		spectrum = transposition_spectrum(primary_pc_set)
		contrast = len(spectrum)-(1+index)
		if contrast not in range(len(spectrum)):
			contrast = 0
		pc_set_progression.extend(neighbor_by_contrast(primary_pc_set, contrast))
	section_length.append(len(pc_set_progression))

	print "\nSection lengths:"
	for item in section_length:
		print str(item)

	print "\nPitch-Class Set Progression:"
	for index, item in enumerate(pc_set_progression):
		print str(index) + ": " + str(item)

	# compose pc_sequence:
	pc_sequence = list()

	print "\nPitch-Class Sequence:"
	for pc_set in pc_set_progression:
		seq = Pc_sequence(pc_set, repeat_chance, repeat_attempts, repeat_loops)
		pc_sequence.append(seq)
		print str(pc_sequence[-1].sequence)

	instrument = ensemble[0]
	track = Track(instrument)
	track.name = instrument.name
	composition = Composition()

	#title = "my title"
	#composition.set_title(title)
	#print composition.title

	#author = "Pierrot"
	#composition.set_author(author)
	#print composition.author

	note = Note()
	track.add_bar(Bar())
	track.bars[-1].set_meter(meter)

	count = 0
	cur_rhythm_cycle = 0
	cur_section = 0

	first_note = False

	for index, item in enumerate(pc_sequence):

		orchestrator = Orchestrator(item, instrument, stability)

		while not orchestrator.completed():

			# select rhythm cycle
			if index == len(pc_sequence)-1:
				cycle = rhythm_cycles[cur_rhythm_cycle]
			else:
				if count == 0:
					cycle = rhythm_cycles[cur_rhythm_cycle]
				elif count % section_length[cur_section] == 0:
					cur_rhythm_cycle += 1
					cur_section += 1
					if cur_rhythm_cycle == len(rhythm_cycles):
						cur_rhythm_cycle = 0
					if cur_section == len(section_length):
						cur_section = 0
					cycle = rhythm_cycles[cur_rhythm_cycle]

			print "\ncount = " + str(count)
			print "rhythm cycle # " + str(cur_rhythm_cycle)
			print "section # " + str(cur_section)
			print "section length = " + str(section_length[cur_section])

			unit = cycle.get_next_unit()

			print "cycle position = " + str(cycle.get_index())
			print "unit value = " + str(unit.get_value())

			if track.bars[-1].is_full():
				track.add_bar(Bar())
				track.bars[-1].set_meter(meter)

			if unit.is_rest():
				print "unit is rest"
				if not track.bars[-1].place_rest(unit.get_value()):
					print "not enough room in bar"
					if track.bars[-1].space_left() == 0:
						print "adding new bar"
						track.add_bar(Bar())
						track.bars[-1].set_meter(meter)
					value_left = track.bars[-1].value_left()
					if track.bars[-1].space_left >= 1.0/unit.get_value():
						print "placing rest"
						track.bars[-1].place_rest(unit.get_value())
					else:
						difference = subtract(unit.get_value(), value_left)
						while difference != 0:
							print "spliting rest across bars"
							track.bars[-1].place_rest(value_left)
							track.add_bar(Bar())
							track.bars[-1].set_meter(meter)
							if space_left >= 1.0/difference:
								track.bars[-1].place_rest(difference)
								break
			else:
				print "unit is note"
				note = orchestrator.next()
				if not first_note:
					first_note = note
				print str(next)
				if not track.bars[-1].place_notes(note, unit.get_value()):
					print "not enough room in bar"
					if track.bars[-1].space_left() != 0:
						value_left = track.bars[-1].value_left()
						print "value left = " + str(value_left)
						cur_beat = track.bars[-1].current_beat
						print "filling in remaining space"
						track.bars[-1].place_notes(note, value_left)

						value_needed = subtract(unit.get_value(), value_left)

						print "adding bars to fit full value"
						track.add_bar(Bar())
						track.bars[-1].set_meter(meter)
						value_bar = track.bars[-1].value_left()

						bars_added = 1
						while 1.0/value_needed > 1.0/value_bar:
							print "adding bar"
							track.add_bar(Bar())
							track.bars[-1].set_meter(meter)
							value_needed = subtract(value_needed, value_bar)
							bars_added+=1

						if not track.bars[-bars_added].place_notes_at(cur_beat, unit.get_value()):
							print "could not fit value"
		count+=1

	note = first_note
	
	composition.add_track(track)

	write_Composition(filename, composition, bpm, repetitions)

	print "\n"
	print repr(composition)

	print "\nCompleted."
	print "\nOutput saved as: " + filename + "\n"

	return
Beispiel #22
0
def play_Music(filename):
    f = open(filename, 'rb')
    data = json.loads(f.read(), encoding='utf8')
    f.close()

    n = data['音符']
    h = data['音高']
    r = data['节拍']
    l = data['组成']
    k = data['调性']
    t = Track()
    b = Bar('C', (4, 4))
    b.place_rest(1)
    t.add_bar(b)
    name = 'CDEFGAB'
    symbol = '!@#$%^&'

    def tran(x):
        if x >= 'a':
            return ord(x) - 87
        elif x == '0':
            return 0.5
        else:
            return float(x)

    f = open(filename, 'rb')
    data = json.loads(f.read(), encoding='utf8')
    f.close()

    n = data['音符']
    h = data['音高']
    r = data['节拍']
    l = data['组成']
    k = data['调性']
    t = Track()
    b = Bar('C', (4, 4))
    b.place_rest(1)
    t.add_bar(b)
    name = 'CDEFGAB'
    symbol = '!@#$%^&'
    for i in range(len(l)):
        rn = list(map(tran, r[l[i]]))
        b = Bar('C', (4 * sum(rn)/8, 4))
        for j in range(len(n[l[i]])):
            if n[l[i]][j] == '0':
                b.place_rest(8 / rn[j])
            else:
                x = symbol.find(n[l[i]][j])
                if x == -1:
                    x = int(n[l[i]][j]) - 1
                    y = name[x]
                else:
                    y = name[x] + '#'
                    print(y)
                note = Note(y, int(h[l[i]][j]))
                note.transpose(k[i])
                b.place_notes(note, 8 / rn[j])
        t.add_bar(b)

    t2 = Track()
    b = Bar('C', (4, 4))
    b.place_rest(1)
    t2.add_bar(b)
    for i in range(int(sum(map(sum, map(lambda x: map(tran, r[x]), l)))) // 8):
        b = Bar('C', (4, 4))
        b.place_notes('C-3', 4)
        b.place_notes('C-7', 4)
        b.place_notes('C-5', 4)
        b.place_notes('C-7', 4)
        t2.add_bar(b)

    m = MidiFile()
    mt = MidiTrack(150)
    mt2 = MidiTrack(150)
    mt3 = MidiTrack(150)
    m.tracks = [mt,mt2,mt3]
    mt.set_instrument(1, 25)
    mt.play_Track(t)
    # for _, _, i in t2.get_notes():
    #     if i is not None:
    #         i[0].set_channel(2)
    # mt2.set_instrument(2, 115)
    # mt2.play_Track(t2)
    # for _, _, i in t.get_notes():
    #     if i is not None:
    #         i[0].set_channel(3)
    # mt3.set_instrument(3, 100)
    # mt3.track_data += mt3.controller_event(3, 7, 30)
    # mt3.play_Track(t)
    # m.write_file('D:/test.midi', False)
    # for i in range(len(l)):
    #     rn = list(map(tran, r[l[i]]))
    #     b = Bar('C', (4 * sum(rn) / 8, 4))
    #     for j in range(len(n[l[i]])):
    #         # if i==0 and j==0:
    #         #     b.place_notes('D-4', 3)
    #         # el
    #         if n[l[i]][j] == '0':
    #             b.place_rest(1 / rn[j])
    #         else:
    #             x = symbol.find(n[l[i]][j])
    #             if x == -1:
    #                 x = int(n[l[i]][j]) - 1
    #                 y = name[x]
    #             else:
    #                 y = name[x] + '#'
    #                 print(y)
    #
    #             note = Note(y, int(h[l[i]][j]))
    #             note.transpose(k[i])
    #             #print(note)
    #             print(rn[j])
    #             #print(b)
    #             b.place_notes(note, 1 / rn[j])
    #     t.add_bar(b)
    #     print(b)

    fluidsynth.init("D:\MyCode\MyPython\AiMusicCoach\GeneralUserSoftSynth\GeneralUserSoftSynth.sf2")
    fluidsynth.set_instrument(1, 1)            #24=Nylon Guitar
                                                # 25=Steel Guitar
                                                # 26=Jazz Guitar
                                                # 27=Clean Guitar
                                                # 28=Muted Guitar
                                                # 29=Overdrive Guitar
                                                # 30=Distortion Guitar
    m.write_file('D:\MyCode\MyPython\AiMusicCoach\Backend\music_file\mysong.midi', False)
    os.system("d: && cd D:\\MyCode\\MyPython\\AiMusicCoach\\fluidsynth-x64\\bin && fluidsynth -F mysong.wav D:/MyCode/MyPython/AiMusicCoach/GeneralUserSoftSynth/GeneralUserSoftSynth.sf2 D:\MyCode\MyPython\AiMusicCoach\Backend\music_file\mysong.midi")
    fluidsynth.play_Track(t, channel=1, bpm=150)
Beispiel #23
0
from improv import generate_solo
from subprocess import call

num_progressions = 4
chords_list = ['CM', 'G7', 'CM7', 'FM7', 'G7', 'Am7', 'G7', 'C#+']
chords_bars = []
for chord in chords_list:
	chord_nc = NoteContainer(chords.from_shorthand(chord))
	bar = Bar()
	bar.place_notes(chord_nc, 1)
	chords_bars.append(bar)
solo_track = Track()
chords_track = Track()
for _ in range(num_progressions):
	for bar in generate_solo(chords_list):
		solo_track.add_bar(bar)
	for bar in chords_bars:
		chords_track.add_bar(bar)

guitar = MidiInstrument()
guitar.instrument_nr = 26
solo_track.instrument = guitar

piano = MidiInstrument()
piano.instrument_nr = 0
chords_track.instrument = piano

song = Composition()
song.add_track(solo_track)
song.add_track(chords_track)
Beispiel #24
0
def write_song(melody):
    unl = keys.get_notes(melody.key)
    note_list = randomList()
    note_list.setDefaultWeight(100)
    note_list.add(unl, recursive=True)
    note_list.add(None, (random.gauss(25, 10)))
    print(note_list.normalisedWeights())
    print(note_list.list)

    wds = randomList()
    td = melody.tempo - 120.0
    #scaling for these is kinda wonky but whatever
    full = 0
    half = 0
    quarter = 0
    eighth = 0
    sixteenth = 0
    if (td < 0):
        #half notes - more often (180) for faster tempos, less often (90) for slower tempos
        half = max(0, random.gauss(120.0 + (td / 2), 60))
        #full notes - 1.25x as often for faster tempos, half as often for slower tempos
        full = max(0, random.gauss((120.0 + (td / 2)) / 2, 60))
        #sixteenth notes - less often (90) for faster tempos, more often (180) for slower tempos
        sixteenth = max(0, random.gauss((120.0 - td), 60))
    else:
        half = max(0, random.gauss(120.0 + (td / 2), 60))
        full = max(0, random.gauss((120.0 + (td / 2)) * 1.25, 60))
        sixteenth = max(0, random.gauss((120.0 - (td / 4)), 60))

    #quarter notes - 120 median always
    quarter = max(0, random.gauss(120, 60))
    #eighth notes - 120 median always
    eighth = max(0, random.gauss(120, 60))

    wds.add(1, full)
    wds.add(2, half)
    wds.add(4, quarter)
    wds.add(8, eighth)
    wds.add(16, sixteenth)

    melody.weights = wds.normalisedWeights()
    sig = random.choice(signatures)
    print(sig)

    t = Track()
    i = 0
    numBars = melody.length

    while (i < numBars):
        b = Bar(melody.key, sig)
        while (b.current_beat != b.length):
            duration = wds.pickWeighted()
            n = note_list.pickWeighted()
            while (n == None
                   and (duration <= 2 or duration > 8 or b.current_beat == 0
                        or melody.raw_song[-1][0] == None)):
                n = note_list.pickWeighted()
            if (b.place_notes(n, duration)):
                melody.raw_song.append((n, duration))
        t.add_bar(b)
        i = i + 1
    return t
import mingus
import mingus.extra.musicxml as musicxml
import mingus.core.notes as notes
import mingus.core.value as value
from mingus.containers import Note
from mingus.containers import Bar
from mingus.containers import Track
import pickle

song = Track()

bar = Bar()

bar.place_notes(Note('C', 4), value.whole)

song.add_bar(bar)
bar = Bar()

bar.place_notes(Note('C', 4), value.half)
bar.place_notes(Note('C', 4), value.half)

song.add_bar(bar)
bar = Bar()

bar.place_notes(Note('C', 4), value.quarter)
bar.place_notes(Note('C', 4), value.quarter)
bar.place_notes(Note('C', 4), value.quarter)
bar.place_notes(Note('C', 4), value.quarter)

song.add_bar(bar)
bar = Bar()
Beispiel #26
0
def main():
    repo = Repo(sys.argv[1])
    factory = cf.ConverterFactory()
    converter = factory.get_converter("mod")
    curtime = datetime.datetime.now()
    if (len(sys.argv) == 3):
        target_file = sys.argv[2]
    else:
        target_file = "gitmelody" + str(curtime.year) + str(curtime.month) + str(curtime.hour) \
            + str(curtime.minute) + str(curtime.second) + ".mid"

    commits = list(repo.iter_commits('master'))

    timesignature = converter.getTimeSignature(commits)
    tsValue = timesignature[0] / timesignature[1]
    print(tsValue)
    print(timesignature)

    #nc = NoteContainer()
    bar = Bar()
    if timesignature != None:
        bar.set_meter((timesignature[0], timesignature[1]))
    t = Track()
    t2 = Track()
    dursum = 0
    tsValue = 1
    c = Composition()
    #durations are between 1 and 128
    for item in commits:
        #note_item = get_note_from_commit(item.stats.total)
        note_item = converter.getNoteFromCommit(item.stats.total)
        if (dursum + (1 / note_item[1]) <= tsValue):
            dursum = dursum + 1 / note_item[1]
            bar.place_notes(note_item[0], note_item[1])
        else:
            dursum = 0
            if (bar.space_left() > 0):
                booleanValue = bool(random.getrandbits(1))
                if booleanValue == True:
                    bar.place_notes(note_item[0], bar.space_left())
                else:
                    bar.place_rest(bar.space_left())
            t.add_bar(bar)
            second_line = converter.getChordOrArpeggio(bar)
            t2.add_bar(second_line)
            bar = Bar()
            bar.set_meter((timesignature[0], timesignature[1]))
    c.add_track(t)
    c.add_track(t2)
    print(bar.meter)

    #bar.place_notes(note_item[0], note_item[1])
    #t.add_notes(note_item[0])

    #print(item.stats.total['insertions'])
    #print(item.stats.additions)
    #print(item.stats.deletions)
    #print(item.stats.total)a

    #nc = NoteContainer(["A", "C", "E"])
    #midi_file_out.write_Track(target_file, t)
    midi_file_out.write_Composition(target_file, c)
Beispiel #27
0
# Generate the first note

generator = NoteGenerator(notes=notes, duration=4)#, conditions={0: condition1})
generator.add_notes_to(bar1, count=4) # This line add the first note to the bar defined above
prev_notes = generator.added_notes

'''
# Generate the second note
notes = note_collection(['D', 'F#', 'A'])
allowed_condition_1 = lambda parameters: True if (parameters['prev_note'] != parameters['current_note']) else False
generator = NoteGenerator(notes=notes, duration=4, allowed_conditions=[allowed_condition_1], parameters={'prev_note': prev_notes[FIRST]})
generator.add_notes_to(bar, count=1) # This line add the second note to the bar defined above
'''

# Add bar to the track
track.add_bar(bar1)

bar2 = Bar()
generator.add_notes_to(bar2, count=4)
track.add_bar(bar2)

bar3 = Bar()
generator.add_notes_to(bar3, count=4)
track.add_bar(bar3)

bar4 = Bar()
generator.add_notes_to(bar4, count=3)

last_note_collection = note_collection(['C', 'E',  'G', 'B'])
last_generator = NoteGenerator(notes=last_note_collection, duration=4)
last_generator.add_notes_to(bar4, count=1)
def generate_longer_fugue(key, subject, nr_parts=1, order_of_parts=None):
    #If subject doesn't fill full bars fill out rest of last bar of subject with rest
    #if last bar is not full
    if not (subject[-1].is_full()):
        #place a rest at the end of the last bar with the length of 1/(remaining fraction of bar)
        subject[-1].place_rest(int(1.0 / subject[-1].space_left()))

    # Create first bar with subject in first voice and rest in second voice.
    rest_1bar = Bar(key)
    rest_1bar.place_rest(1)
    first_voice = copy.deepcopy(subject)

    #Add same amount of "rest bars" as the number of bars in the subject
    for i in range(len(subject)):
        second_voice.add_bar(copy.deepcopy(rest_1bar))

    total_nr_evolutionary_parts = 3 + 3 * nr_parts

    # Create second bar with answer in second voice.
    answer = Track_Functions.create_answer(subject, key)

    Track_Functions.add_tracks(second_voice, answer)

    # Generate countersubject
    nr_current_generated = 1
    eg_counter = EvolutionaryGenerator(key,
                                       nr_bars=1,
                                       fitness_function='counter',
                                       input_melody=subject,
                                       nr_generations=counter_nr_generations)
    print(
        f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
    )
    nr_current_generated += 1
    eg_counter.run_evolution()
    counter_subject = copy.deepcopy(eg_counter.best_individual)

    Track_Functions.add_tracks(first_voice, counter_subject)

    # Save subject, answer and countersubject
    first_voice_first_part = copy.deepcopy(first_voice)
    second_voice_first_part = copy.deepcopy(second_voice)

    # Save bar 2 for later modulation
    bar_prev = first_voice[-1]

    variants = ['Minor', 'Reverse', 'Inverse']
    iParts = 0

    if order_of_parts is None:
        order_of_parts = []
        for i in range(nr_parts):
            rVariant = rnd.choice(variants)
            order_of_parts.append(rVariant)

    while iParts < nr_parts:
        current_variant = order_of_parts[iParts]

        if current_variant == 'Minor':
            # Generate development in minor
            # Transposed -3 to minor (stämma i second voice tills vidare tom)
            new_first_voice = Track_Functions.transpose_to_relative_minor(
                first_voice, key, False)
            new_second_voice = Track_Functions.transpose_to_relative_minor(
                second_voice, key, False)

            bar_after = new_first_voice[0]

            # Generate harmony in second voice first bar
            eg_harmony = EvolutionaryGenerator(
                key,
                nr_bars=1,
                fitness_function='harmony',
                input_melody=Track().add_bar(copy.deepcopy(
                    new_first_voice[0])),
                nr_generations=harmony_nr_generations)

            print(
                f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
            )
            nr_current_generated += 1
            eg_harmony.run_evolution()

            new_second_voice[0] = eg_harmony.best_individual[0]

        elif current_variant == 'Reverse':
            # Generate reverse development

            new_first_voice = Track_Functions.reverse(first_voice_first_part,
                                                      key)
            new_second_voice = Track_Functions.reverse(second_voice_first_part,
                                                       key)

            bar_after = new_first_voice[0]

            # Generate harmony in second voice first bar
            eg_harmony = EvolutionaryGenerator(
                key,
                nr_bars=1,
                fitness_function='harmony',
                input_melody=Track().add_bar(copy.deepcopy(
                    new_first_voice[1])),
                nr_generations=harmony_nr_generations)

            print(
                f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
            )
            nr_current_generated += 1
            eg_harmony.run_evolution()
            new_second_voice[1] = eg_harmony.best_individual[0]

        elif current_variant == 'Inverse':
            # Generate inverse development

            new_first_voice = Track_Functions.inverse(first_voice_first_part)
            new_second_voice = Track_Functions.inverse(second_voice_first_part)

            bar_after = new_first_voice[0]

            # Generate harmony in second voice first bar
            eg_harmony = EvolutionaryGenerator(
                key,
                nr_bars=1,
                fitness_function='harmony',
                input_melody=Track().add_bar(copy.deepcopy(
                    new_first_voice[0])),
                nr_generations=harmony_nr_generations)

            print(
                f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
            )
            nr_current_generated += 1
            eg_harmony.run_evolution()
            new_second_voice[0] = eg_harmony.best_individual[0]

        # Generate the two bars linking this new part to the previous parts

        eg_modulate = EvolutionaryGenerator(
            key,
            nr_bars=2,
            fitness_function='modulate',
            from_bar=bar_prev,
            to_bar=bar_after,
            nr_generations=modulate_nr_generations)

        print(
            f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
        )
        nr_current_generated += 1
        eg_modulate.run_evolution()
        modulate_first_voice = copy.deepcopy(eg_modulate.best_individual)

        # Generate second voice as harmony to this linking part

        eg_second_voice_modulate = EvolutionaryGenerator(
            key,
            nr_bars=2,
            fitness_function='harmony',
            input_melody=modulate_first_voice,
            nr_generations=harmony_nr_generations)

        print(
            f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
        )
        nr_current_generated += 1
        eg_second_voice_modulate.run_evolution()
        modulate_second_voice = copy.deepcopy(
            eg_second_voice_modulate.best_individual)

        # Add new bars to the voice tracks
        Track_Functions.add_tracks(first_voice, modulate_first_voice)
        Track_Functions.add_tracks(second_voice, modulate_second_voice)

        Track_Functions.add_tracks(first_voice, new_first_voice)
        Track_Functions.add_tracks(second_voice, new_second_voice)

        bar_prev = first_voice[-1]

        iParts += 1

    # Create canon in bar 9 and 10.
    # subject i first voice
    # second voice is subject but shifted (half a bar for now)

    canon_first_voice = Track()
    canon_first_voice.add_bar(copy.deepcopy(subject[0]))

    bar_after = canon_first_voice[0]

    canon_second_voice = Track_Functions.shift(subject, 2)

    # Create modulation from minor to major in 7 and 8

    eg_modulate_to_major = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='modulate',
        from_bar=bar_prev,
        to_bar=bar_after,
        nr_generations=modulate_nr_generations)

    print(
        f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
    )
    nr_current_generated += 1
    eg_modulate_to_major.run_evolution()
    modulate_back_first_voice = copy.deepcopy(
        eg_modulate_to_major.best_individual)

    # Generate second voice as harmony to the first voice in bar 7 and 8

    eg_second_voice_modulate_back = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='harmony',
        input_melody=modulate_first_voice,
        nr_generations=harmony_nr_generations)

    print(
        f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
    )
    nr_current_generated += 1
    eg_second_voice_modulate_back.run_evolution()
    modulate_back_second_voice = copy.deepcopy(
        eg_second_voice_modulate.best_individual)

    # Add bar 7-10 to the voice tracks
    Track_Functions.add_tracks(first_voice, modulate_back_first_voice)
    Track_Functions.add_tracks(second_voice, modulate_back_second_voice)

    Track_Functions.add_tracks(first_voice, canon_first_voice)
    Track_Functions.add_tracks(second_voice, canon_second_voice)

    # Add cadence ending to second voice
    Track_Functions.second_voice_ending(second_voice, key)

    second_voice_ending = Track().add_bar(copy.deepcopy(second_voice[-3]))
    second_voice_ending.add_bar(copy.deepcopy(second_voice[-2]))

    # Generate harmony to cadence in first voice
    first_voice_last_bar = Track_Functions.first_voice_ending(first_voice, key)

    eg_first_voice_ending = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='ending',
        input_melody=second_voice_ending,
        from_bar=subject[0],
        to_bar=first_voice_last_bar[0],
        nr_generations=harmony_nr_generations)

    print(
        f"Generating evolutionary part {nr_current_generated} of {total_nr_evolutionary_parts}"
    )
    eg_first_voice_ending.run_evolution()
    first_voice_ending = copy.deepcopy(eg_first_voice_ending.best_individual)
    Track_Functions.add_tracks(first_voice, first_voice_ending)
    Track_Functions.add_tracks(first_voice, first_voice_last_bar)

    #Add voices together to create a final composition
    fugue.add_track(first_voice)
    fugue.add_track(second_voice)

    #Generate lilypond file for fugue named final_fugue (removed for submission)
    finished_fugue = LilyPond.from_Composition(fugue)
    to_LilyPond_file(finished_fugue, "final_fugue")

    #Generate MIDI output for fugue named final_fugue
    midi_file_out.write_Composition("final_fugue.mid", fugue)
    return
Beispiel #29
0
def Track_from_list(listt=[[[0.0, 8.0, None], [0.125, 16.0, ['C-6']]]]):
    t = Track()
    for bars in listt:
        t.add_bar(bars)
    return t
def generate_fugue(key, subject):

    #If subject doesn't fill full bars fill out rest of last bar of subject with rest
    #if last bar is not full
    if not (subject[-1].is_full()):
        #place a rest at the end of the last bar with the length of 1/(remaining fraction of bar)
        subject[-1].place_rest(int(1.0 / subject[-1].space_left()))

    # Create first bar with subject in first voice and rest in second voice.
    rest_1bar = Bar(key)
    rest_1bar.place_rest(1)
    first_voice = copy.deepcopy(subject)

    #Add same amount of "rest bars" as the number of bars in the subject
    for i in range(len(subject)):
        second_voice.add_bar(copy.deepcopy(rest_1bar))

    # Create second bar with answer in second voice.
    answer = Track_Functions.create_answer(subject, key)

    #second_voice = second_voice + answer
    Track_Functions.add_tracks(second_voice, answer)

    # Generate countersubject
    eg_counter = EvolutionaryGenerator(key,
                                       nr_bars=1,
                                       fitness_function='counter',
                                       input_melody=subject,
                                       nr_generations=counter_nr_generations)
    print('Generating evolutionary part 1 of 7')
    eg_counter.run_evolution()
    counter_subject = copy.deepcopy(eg_counter.best_individual)

    Track_Functions.add_tracks(first_voice, counter_subject)

    # Save bar 2 for later modulation
    bar_2 = first_voice[-1]

    # Generate development in minor in bar 5 and 6.
    # Transposed -3 to minor + (stämma i för second voice tills vidare tom)
    minor_first_voice = Track_Functions.transpose_to_relative_minor(
        first_voice, key, False)
    minor_second_voice = Track_Functions.transpose_to_relative_minor(
        second_voice, key, False)

    bar_5 = minor_first_voice[0]

    # Generate harmony in second voice in bar 5
    eg_harmony_minor = EvolutionaryGenerator(
        key,
        nr_bars=1,
        fitness_function='harmony',
        input_melody=Track().add_bar(copy.deepcopy(minor_first_voice[0])),
        nr_generations=harmony_nr_generations)

    print('Generating evolutionary part 2 of 7')
    eg_harmony_minor.run_evolution()

    minor_second_voice[0] = eg_harmony_minor.best_individual[0]

    # Generate bar 3 and 4 as a modulation between bar 2 and 5

    eg_modulate_to_minor = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='modulate',
        from_bar=bar_2,
        to_bar=bar_5,
        nr_generations=modulate_nr_generations)

    print('Generating evolutionary part 3 of 7')
    eg_modulate_to_minor.run_evolution()
    modulate_first_voice = copy.deepcopy(eg_modulate_to_minor.best_individual)

    # Generate second voice as harmony to the first voice in bar 3 and 4

    eg_second_voice_modulate = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='harmony',
        input_melody=modulate_first_voice,
        nr_generations=harmony_nr_generations)

    print('Generating evolutionary part 4 of 7')
    eg_second_voice_modulate.run_evolution()
    modulate_second_voice = copy.deepcopy(
        eg_second_voice_modulate.best_individual)

    # Add bar 3-6 to the voice tracks
    Track_Functions.add_tracks(first_voice, modulate_first_voice)
    Track_Functions.add_tracks(second_voice, modulate_second_voice)

    Track_Functions.add_tracks(first_voice, minor_first_voice)
    Track_Functions.add_tracks(second_voice, minor_second_voice)

    bar_6 = first_voice[-1]

    # Create canon in bar 9 and 10.
    # subject i first voice
    # second voice is subject but shifted (half a bar for now)

    canon_first_voice = Track()
    canon_first_voice.add_bar(copy.deepcopy(subject[0]))

    bar_9 = canon_first_voice[0]

    canon_second_voice = Track_Functions.shift(subject, 2)

    # Create modulation from minor to major in 7 and 8

    eg_modulate_to_major = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='modulate',
        from_bar=bar_6,
        to_bar=bar_9,
        nr_generations=modulate_nr_generations)

    print('Generating evolutionary part 5 of 7')
    eg_modulate_to_major.run_evolution()
    modulate_back_first_voice = copy.deepcopy(
        eg_modulate_to_major.best_individual)

    # Generate second voice as harmony to the first voice in bar 7 and 8

    eg_second_voice_modulate_back = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='harmony',
        input_melody=modulate_first_voice,
        nr_generations=harmony_nr_generations)

    print('Generating evolutionary part 6 of 7')
    eg_second_voice_modulate_back.run_evolution()
    modulate_back_second_voice = copy.deepcopy(
        eg_second_voice_modulate.best_individual)

    # Add bar 7-10 to the voice tracks
    Track_Functions.add_tracks(first_voice, modulate_back_first_voice)
    Track_Functions.add_tracks(second_voice, modulate_back_second_voice)

    Track_Functions.add_tracks(first_voice, canon_first_voice)
    Track_Functions.add_tracks(second_voice, canon_second_voice)

    # Add cadence ending to second voice
    Track_Functions.second_voice_ending(second_voice, key)

    second_voice_ending = Track().add_bar(copy.deepcopy(second_voice[-3]))
    second_voice_ending.add_bar(copy.deepcopy(second_voice[-2]))

    # Generate harmony to cadence in first voice
    first_voice_last_bar = Track_Functions.first_voice_ending(first_voice, key)

    eg_first_voice_ending = EvolutionaryGenerator(
        key,
        nr_bars=2,
        fitness_function='ending',
        input_melody=second_voice_ending,
        from_bar=subject[0],
        to_bar=first_voice_last_bar[0],
        nr_generations=harmony_nr_generations)

    print('Generating evolutionary part 7 of 7')
    eg_first_voice_ending.run_evolution()
    first_voice_ending = copy.deepcopy(eg_first_voice_ending.best_individual)
    Track_Functions.add_tracks(first_voice, first_voice_ending)
    Track_Functions.add_tracks(first_voice, first_voice_last_bar)

    #Add voices together to create a final composition
    fugue.add_track(first_voice)
    fugue.add_track(second_voice)

    #Generate lilypond file for fugue named final_fugue
    finished_fugue = LilyPond.from_Composition(fugue)
    to_LilyPond_file(finished_fugue, "final_fugue")

    #Generate MIDI output for fugue named final_fugue
    midi_file_out.write_Composition("final_fugue.mid", fugue)
Beispiel #31
0
        first = random.choice([0, 1, 2, 3, 4])
        second = random.choice([-1, 1])
        third = second * 2
        # if you get a triplet just put three in there for good measure
        gypsy_bar.place_notes(gypsy_scale[first], duration=duration)
        gypsy_bar.place_notes(gypsy_scale[first + second], duration=duration)
        gypsy_bar.place_notes(gypsy_scale[first + third], duration=duration)
    else:
        note = random.choice(gypsy_scale)
        if note is None:
            gypsy_bar.place_rest(duration=duration)
        else:
            gypsy_bar.place_notes(note, duration=duration)
print(gypsy_bar)
midi_file_out.write_Bar("gypsy_bar_" + version + ".mid", gypsy_bar)
gypsy_track.add_bar(gypsy_bar)

print(gypsy_track)

drum_track = Track()
kick = drums["kick"]
snare = drums["snare"]
hat = drums["hatclosed"]
# for dbar in range(0, 20):
drum_bar = Bar()
drum_bar.place_notes(NoteContainer([kick, hat]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
drum_bar.place_notes(NoteContainer([kick, hat, snare]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
drum_bar.place_notes(NoteContainer([kick, hat]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
Beispiel #32
0
from mingus.containers import Note
from mingus.containers import NoteContainer
from mingus.containers import Bar
from mingus.containers import Track
from mingus.containers.instrument import Instrument, Piano, Guitar
from mingus.containers import Composition
from mingus.midi.midi_file_out import write_Composition

eb = Note("Eb", 4)
g = Note("G", 4)
bb = Note("Bb", 4)
n = NoteContainer([eb, g, bb])
c = Composition()
c.set_author('Dusty Carver', '*****@*****.**')
c.set_title('Late Nights')
t = Track(Guitar())
b = Bar('Eb', (4, 4))
b.place_notes(n, 4)
b.place_notes(n, 4)
b.place_notes(n, 4)
b.place_notes(None, 4)
t.add_bar(b)
c.add_track(t)

write_Composition("one.mid", c)