示例#1
0
def main():
    # REPLACE WITH RELEVANT PATHS
    path_to_midi = '../../../Xylo/midis/' 
    path_to_log = '../../../Xylo/logs/'
    
    # F-3 to F-6 would be 37 keys. are we getting rid of 'F-3' or 'F-6'?
    low = Note('F-3')
    high = Note('F-6')
    xylo = create_instrument(low, high)
    
    infile = get_name('in') 
    c, bpm = MIDI_to_Composition(path_to_midi + infile)
    write_log(c, bpm, path_to_log + infile)
    
    # query user to select tracks we actually want from the midi
    c.selected_tracks = select_tracks(c, bpm, xylo)
    
    # INSPECT LOG TO SEE WHICH TRACK NUMBERS YOU WANT INCLUDED AND 
    # PUT THEM INTO THE BELOW LIST
    # c.selected_tracks = [1] # for mhall, only the track at index 1 is to be included
    
    # ratio of highest note value to keep in composition to beat unit.
    # e.g. if meter is 4/4, then a 'cutoff' of 2 would eliminate any
    # notes whose value exceeds 8 (anything briefer than an eighth note)
    cutoff = [8] * len(c.selected_tracks)
    
    # composition containing only the selected tracks, the correct notes, 
    # with everything transposed w/in the range of the instrument
    c = rebuild_composition(c, xylo, cutoff)
    
    # seconds it takes for motor to step the necessary amount to drop
    # a ball
    step_time = 0.1
    # multiply BPM by the ratio of smallest gap between 
    # a note played consecutively and step_time -- only if this number 
    # is less than 1  
    # bpm *= slow_down_composition(c, bpm, step_time)
    # print(bpm)
    
    play_comp_to_user(c, bpm)
    
    # check that everything sounds ok with selected tracks, removed notes,
    # and transposition 
    outfile = get_name('out', infile)
    write_Composition(path_to_midi + outfile, c, bpm)
    
    # TODO: replace with actual ordering once known. ordering by 
    # distance from device center
    lsa_ordering = ['F-3', 'F#-3', 'G-3', 'G#-3', 'A-3', 'A#-3', 'B-3', 
                    'C-4', 'C#-4', 'D-4', 'D#-4', 'E-4', 'F-4', 'F#-4', 
                    'G-4', 'G#-4', 'A-4', 'A#-4', 'B-4', 'C-5', 'C#-5', 
                    'D-5', 'D#-5', 'E-5', 'F-5', 'F#-5', 'G-5', 'G#-5', 
                    'A-5', 'A#-5', 'B-5', 'C-6', 'C#-6', 'D-6', 'D#-6', 
                    'E-6', 'F-6']
    # don't need to pass xylo here -- range contained in c[0]
    pb = create_playback_events(c, bpm, xylo, lsa_ordering)
    send_to_Arduino(pb)
    write_log(c, bpm, path_to_log + outfile, pb)
示例#2
0
    def to_midi(self, fp=''):
        if len(fp)>0:
            outf = r'C:\Users\Sam\Documents\Sidewinder\local files\\'+f'{fp}.mid'
        else:
            outf = r'C:\Users\Sam\Documents\Sidewinder\local files\midi_out.mid'

        if type(self.source) == Composition:
            midi_file_out.write_Composition(outf, self.source, repeat=0, verbose=True)
        elif type(self.passage) == Track:
            midi_file_out.write_Track(outf, self.passage, repeat=0, verbose=True)
示例#3
0
文件: songs.py 项目: acordovap/amg
    async def run(self):
        while await self.receive():  # flush messages
            pass

        c = Composition()
        c.set_author("amg")
        c.set_title(CFG.OUTPUT_PREFIX + self.agent.name)
        c.add_track(self.agent.get("melody_track"))
        c.add_track(self.agent.get("accompaniment_track"))
        # fluidsynth.init("4U-Yamaha C5 Grand-v1.5.sf2", "alsa")
        # fluidsynth.play_Composition(c)
        midi_file_out.write_Composition(
            CFG.OUTPUT_FOLDER + CFG.OUTPUT_PREFIX + self.agent.name + ".mid",
            c, CFG.SONG_TEMPO)
        l = lilypond.from_Composition(c)
        extra = "  \\score { \\new PianoStaff << \\set PianoStaff.instrumentName = #\"Piano  \" \\new Staff = \"upper\" \\upper \\new Staff = \"lower\" \\lower  >> \\layout { }  }"
        l2 = l.replace("{ {", "upper = {x {x", 1).replace(
            "{ {", "lower = { {", 1).replace("{x {x", "{ {", 1) + extra
        # print("<lilipond-"+CFG.OUTPUT_FOLDER+CFG.OUTPUT_PREFIX+self.agent.name+">\n"+l2)
        lilypond.to_pdf(
            l2, CFG.OUTPUT_FOLDER + CFG.OUTPUT_PREFIX + self.agent.name)
        self.agent.presence.set_presence(
            state=PresenceState(available=True, show=PresenceShow.AWAY))
        self.set_next_state(S_FINISHED)
示例#4
0
def export(melody_track, chords, key, time_sig, bpm, file):
    i = Instrument()
    i.instrument_nr = 1
    t2 = Track()
    for i in range(0, len(chords)):
        b = Bar(key, time_sig)
        if len(chords[i][0]) > 5:
            b.place_notes(None, 1)
        else:
            b.place_notes(NoteContainer(chords[i]), 1)
        t2 + b

    c = Composition()
    c.add_track(melody_track)
    c.add_track(t2)

    out_dir = 'out'

    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    mid = file.split('/')[-1]
    if os.path.exists(out_dir + '/' + mid):
        os.remove(out_dir + '/' + mid)
    MidiFileOut.write_Composition(out_dir + '/' + mid, c, bpm)

    file = out_dir + '/' + mid

    sys.argv.append('')
    sys.argv.append('')

    sys.argv[1] = "--midi-file=" + file
    sys.argv[2] = "--out-dir=" + out_dir

    midi.main()
    if os.path.exists(file):
        os.remove(file)
示例#5
0
            random.choice(possible_fills)
    for num in range(0, BAR_NUMBER):
        b = Bar()
        for i2 in range(0, 8):
            n = NoteContainer()
            n.add_notes(notes[num * 8 + i2])
            b.place_notes(n, 8)
        drumtrack.add_bar(b)

b = Bar()
b.place_notes([cc, bd], 4)

drumtrack.add_bar(b)
song.add_track(drumtrack)

midi_file_out.write_Composition("song.mid", song, bpm=random.randint(8, 14) * 10)
print "Wrote to file..."

output = False
MUSESCORE_PATH = 'D:\\Program Files (x86)\\MuseScore 2\\bin\\MuseScore.exe'  # Bad environment detection
if os.path.isfile(MUSESCORE_PATH) and output:
    subprocess.Popen("taskkill /F /IM WWAHost.exe").communicate()  # Kill music app, wait until done
    subprocess.Popen("taskkill /F /IM MuseScore.exe").communicate()  # Kill musescore
    call = '"' + MUSESCORE_PATH + '" ' + '-o "song.mp3" song.mid'  # Convert midi to mp3 using musescore
    subprocess.Popen(call).communicate()
    print "Outputted mp3... opening."
    os.startfile('song.mp3') # open both files
    os.startfile('song.mid')


示例#6
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)
示例#7
0
    def parse_varbyte_as_int(self, fp, return_bytes_read=True):
        """Read a variable length byte from the file and return the
        corresponding integer."""
        result = 0
        bytes_read = 0
        r = 0x80
        while r & 0x80:
            try:
                r = self.bytes_to_int(fp.read(1))
                self.bytes_read += 1
            except:
                raise IOError("Couldn't read variable length byte from file.")
            if r & 0x80:
                result = (result << 7) + (r & 0x7F)
            else:
                result = (result << 7) + r
            bytes_read += 1
        if not return_bytes_read:
            return result
        else:
            return (result, bytes_read)


if __name__ == "__main__":
    from sys import argv
    from mingus.midi import fluidsynth, midi_file_out

    fluidsynth.init(argv[2])
    (m, bpm) = MIDI_to_Composition(argv[1])
    midi_file_out.write_Composition("test.mid", m, bpm)
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)
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
示例#10
0
 def write_midi(self, outfile):
     midi_file_out.write_Composition(outfile,
                                     self.composition,
                                     bpm=self.tempo)
示例#11
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)
示例#12
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)
示例#13
0
def write_comp(c, bpm, filename):
    write_Composition(filename, c, bpm)
示例#14
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)