예제 #1
0
파일: song.py 프로젝트: tewe/canta
class MingusSong:
    def __init__(self):
        self.composition = Composition()
        self.path = ''
        self.song_name = ''
        self.bar_length = 16

    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]

    def generate_pictures(self):
        ''' Generates pictures of the lines of notes '''
        for k, track in enumerate(self.composition.tracks):
            self.generate_picture(k)

    def generate_picture(self, k):
        ''' Generates picture of the lines k '''
        img_path = os.path.join(self.path, 'media', 'images')
        if not os.path.exists(img_path):
            os.makedirs(img_path)
        import tempfile
        tmp_dir = tempfile.mkdtemp()
        track = self.composition.tracks[k]
        ltrack = LilyPond.from_Track(track)
        tmp_file = os.path.join(tmp_dir, 'tmp_file')
        lily_str = li_header + ltrack
        LilyPond.save_string_and_execute_LilyPond(lily_str, tmp_file, '-fps')
        img_file = os.path.join(img_path, self.song_name + str(k) + '.png')
        gs_cmd = 'gs -dBATCH -dNOPAUSE -g2048x256 -q -r273.5 ' \
                +'-sDEVICE=pngalpha -sOutputFile="%s" "%s"' \
                % (img_file, tmp_file + '.ps')
        from subprocess import Popen
        p = Popen(gs_cmd, shell=True)
        sts = os.waitpid(p.pid, 0)
        os.unlink(tmp_file + '.ps')
        os.rmdir(tmp_dir)
예제 #2
0
파일: minevra.py 프로젝트: 9ae/3tonic
def fib_song():
    fluidsynth.init('soundfonts/grand_piano.sf2')
    comp = Composition()
    comp.add_track(fib_seq())
    comp.add_track(fib_seq(offset=4))
    comp.add_track(fib_seq(offset=8))
    fluidsynth.play_Composition(comp)
예제 #3
0
def generate_composition(pattern, progression_type, nb_bars, key="C", rythm=60):
    fluidsynth.init("198_u20_Electric_Grand.SF2") # permet d'initialiser l'instrument
    newComposition = Composition()

    progression_list = on_progression_type_change(progression_type, nb_bars)
    left_hand = generate_pattern(progression_list, key, pattern, nb_bars)
    newComposition.add_track(left_hand)
    MidiFileOut.write_Composition("myComposition.mid", newComposition, rythm, False)
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
예제 #5
0
def tests_to_mingus_composition():
    # Create a composition, and add the vocal tracks to it.
    composition = Composition()
    composition.set_title('Counterpoint Exercise', '')
    composition.set_author(author, '')

    # Set up our vocal 'tracks' with the notes, key, meter defined in tracks.py
    tracks = {}
    for voice in [Soprano, Alto, Tenor, Bass]:
        if len(melodies[voice.name]):
            tracks[voice.name] = Track(instrument=voice())
            tracks[voice.name].add_bar(Bar(key=key, meter=meter))
            tracks[voice.name].name = voice.name
            for note in melodies[voice.name]:
                tracks[voice.name].add_notes(*note)
            composition.add_track(tracks[voice.name])
    return composition
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
예제 #7
0
    def buildComposition(self, compose):
        """
        function to parse file into a composition
        :param compose: contents of midi file
        :return: tuple containing composition and length of composition
        """
        c = Composition()
        count = 0
        #get components
        for track in compose:
            t = self.track
            for bar in track:
                for info in bar:
                    #get note information and duration
                    t.add_notes(info[2], duration=info[1])
                    count = round(count + info[0], 2)
            c.add_track(t)

        return c, count
예제 #8
0
def generate_composition(pattern_index, progression_type, nb_bars, mode='none', key="C", rythm=60):
    fluidsynth.init("198_u20_Electric_Grand.SF2") # permet d'initialiser l'instrument
    newComposition = Composition()
    progression_list = on_progression_type_change(progression_type, nb_bars)
    
     # truc pour la main droite
    if nb_bars == 1 :
        phrase_list = choose_phrases(key, mode, nb_bars)
        right_hand = use_phrase(phrase_list, progression_list, nb_bars, pattern_index, mode='none', key="C")
    else :
        chorus = generate_chorus(progression_list, pattern_index, mode, key)
        #chorus retourne : une phrase de debut, une phrase de fin, 3 bars fixes
        phrase_list = choose_first_phrases(nb_bars, key, mode, chorus[1], chorus[2], pattern_index)
        right_hand = generate_long_right_hand(phrase_list, progression_list, nb_bars, pattern_index, mode, key, chorus)
    
    newComposition.add_track(right_hand)
    
    left_hand = generate_pattern(progression_list, key, pattern_index, nb_bars)
    newComposition.add_track(left_hand)
    MidiFileOut.write_Composition("myCompo.mid", newComposition, rythm, False)
   
    return newComposition
예제 #9
0
def setup_tracks(midi_file_out=None):
    from tracks import melodies, cantus_firmus, key, meter, species, author
    # Create a composition, and add the vocal tracks to it.
    composition = Composition()
    composition.set_title('Counterpoint Exercise', '')
    composition.set_author(author, '')

    # Set up our vocal 'tracks' with the notes, key, meter defined in tracks.py
    tracks = {}
    for voice in [Soprano, Alto, Tenor, Bass]:
        if len(melodies[voice.name]):
            tracks[voice.name] = Track(instrument=voice())
            tracks[voice.name].add_bar(Bar(key=key, meter=meter))
            tracks[voice.name].name = voice.name
            for note in melodies[voice.name]:
                tracks[voice.name].add_notes(*note)
            composition.add_track(tracks[voice.name])

    if midi_file_out is not None:
        # Save the midi file!
        write_Composition(midi_file_out, composition, verbose=True)

    return composition, [], species
예제 #10
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)
예제 #11
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)
예제 #12
0
def vexflow_to_mingus_composition(melodies):
    # Create a composition, and add the vocal tracks to it.
    composition = Composition()
    composition.set_title('Counterpoint Exercise', '')
    composition.set_author(author, '')

    # Set up our vocal 'tracks' with the notes, key, meter defined in tracks.py
    tracks = {}
    for voice in [Soprano, Alto, Tenor, Bass]:
        lower_name = voice.name.lower()
        if lower_name in melodies and melodies[lower_name]:
            tracks[voice.name] = Track(instrument=voice())
            tracks[voice.name].add_bar(Bar(key=key, meter=meter))
            tracks[voice.name].name = voice.name
            for bar in melodies[lower_name]:
                for pitch, duration in bar:
                    pitch = pitch.replace('/', '-').upper()
                    if duration.endswith('r'):
                        pitch = None
                        duration = duration[:-1]
                    duration = inv_durations[duration]
                    tracks[voice.name].add_notes(pitch, duration)
            composition.add_track(tracks[voice.name])
    return composition
예제 #13
0
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)

track.add_bar(bar4)

# Add track to the composition
composition.add_track(track)

# Print the summary of the composition
print(composition)

# Export to a MIDI file
mingus.midi.midi_file_out.write_Composition(pre + "melody generated at " + str(datetime.now()) + ".mid", composition, bpm=80, repeat=0, verbose=False)
예제 #14
0
	name = ''
	range = (Note('C', 0), Note('C', 10))
	clef = 'Bass'
	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)
예제 #15
0
trackmain = Track()
# here is where you set the actual instrument

print "Melody instrument: " + trackmain.set_instrument(instr).names[instr] + " ({})".format(instr)

s = SongGen.Song()
trackmain = s.generate(chorus, verse, bridge, trackmain.track)

# LAST BAR
b = Bar()
n = Note('C', 4)
n.set_channel(1)
b.place_notes(n, 4)

trackmain.add_bar(b)
song.add_track(trackmain)

# END MELODY #


# BEGIN HARMONY #

# setup verse
ini = [False] * 5
ini[random.randint(0, 4)] = True
# instr = random.randint(1, 104)
instr = 33
vel = [32, 48]
channel = 2

# instrument in this function does not matter if you are combining generated tracks
예제 #16
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)
    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)
예제 #18
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)
예제 #19
0
파일: to_midi.py 프로젝트: djfoote/atunal
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)

MidiFileOut.write_Composition("test.mid", song)

filename = "test.mid"
call("timidity -Ow {0}".format(filename), shell=True)
# fluidsynth -F test.wav -i -n -T wav soundfont.sf2 test.mid
예제 #20
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
예제 #21
0
파일: song.py 프로젝트: spiderbit/canta-ng
class MingusSong:

    def __init__(self):
        self.composition = Composition()
        self.path = ''
        self.song_name = ''
        self.bar_length = 16

    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]


    def generate_pictures(self):
        ''' Generates pictures of the lines of notes '''
        for k, track in enumerate(self.composition.tracks):
            self.generate_picture(k)


    def generate_picture(self, k):
        ''' Generates picture of the lines k '''
        img_path = os.path.join(self.path, 'media', 'images')
        if not os.path.exists(img_path):
            os.makedirs(img_path)
        import tempfile
        tmp_dir = tempfile.mkdtemp()
        track = self.composition.tracks[k]
        ltrack = LilyPond.from_Track(track)
        tmp_file = os.path.join(tmp_dir, 'tmp_file')
        lily_str = li_header + ltrack
        LilyPond.save_string_and_execute_LilyPond(lily_str, tmp_file, '-fps')
        img_file = os.path.join(img_path, self.song_name + str(k) + '.png')
        gs_cmd = 'gs -dBATCH -dNOPAUSE -g2048x256 -q -r273.5 ' \
                +'-sDEVICE=pngalpha -sOutputFile="%s" "%s"' \
                % (img_file, tmp_file + '.ps')
        from subprocess import Popen
        p = Popen(gs_cmd, shell=True)
        sts = os.waitpid(p.pid, 0)
        os.unlink(tmp_file + '.ps')
        os.rmdir(tmp_dir)
예제 #22
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)