Пример #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]
Пример #2
0
def main():
	fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa")
	solution = [52,52,53,55,55,53,52,50,48,48,50,52,52,50,50]
	#testSol = [1,3,53,55,55,53,52,50,48,48,50,52,52,50,50]
	population = createInitialPopulation(250, len(solution))
	#t = Track()
	#for note in findMostFit(population,solution):
	#	t + note
	#fluidsynth.play_Track(t,1)
	generation = 1
	highestFitness = calcFitness(findMostFit(population, solution), solution)
	print("Generation: 1")
	print("Initial Highest Fitness: " + str(highestFitness))
	#print(calcFitness(testSol,solution))

	while highestFitness < 1:
		population = createNewPopulation(population, solution, .01)
		generation = generation + 1
		highestFitness = calcFitness(findMostFit(population, solution), solution)
		print("Generation: " + str(generation))
		print("Highest Fitness level: " + str(highestFitness))
		if generation % 10 == 0:
			print("hi")
			t = Track()
			for noteInt in findMostFit(population,solution):
				newNote = Note()
				newNote.from_int(noteInt)
				t + newNote
			fluidsynth.play_Track(t,1)
			#time.sleep(10)
	t = Track()
	for note in findMostFit(population,solution):
		t + note
	fluidsynth.play_Track(t,1)
Пример #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   
Пример #4
0
def vector_to_midi(arr, filename="nice.midi"):
  track = Track()
  for note_arr in arr:
    note_num = int(np.argmax(note_arr))
    note = Note()
    note.from_int(note_num - 3)
    track.add_notes(note)
  write_Track(filename, track)
  print("Done!")
Пример #5
0
 async def on_start(self):
     self.agent.set("current_bar_no", 0)  # inicializa "current_bar_no" en 0
     # self.agent.set("tempo", 120)
     # self.agent.set("key", "C")
     self.agent.set("melody_track", Track())
     self.agent.set("accompaniment_track", Track())
     self.agent.set("current_melody_bar",
                    Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE))
     self.agent.set("current_accompaniment_bar",
                    Bar(CFG.SONG_KEY_SIGNATURE, CFG.SONG_TIME_SIGNATURE))
Пример #6
0
    def __init__(self):
        """
        function to initialize PianoPlayer class
        """
        self.track = Track(Piano())
        self.notes = []

        #initialize keys
        for i in range(21, 109):
            self.notes.append(i)
        self.matrix = {}
        for n in self.notes:
            i = int(n)
            self.matrix[i] = [0] * 10
Пример #7
0
def input_list(list_of_note_tuples):
    #track to return
    track = Track()

    #For every tuple in input
    for (name, duration) in list_of_note_tuples:

        #If we can't add note (duration is too long)
        if not (track.add_notes(name, duration)):
            #Calculate new duration to fit bar and add note
            space_left = track[-1].space_left()
            track.add_notes(name, int(1.0 / space_left))

    return track
Пример #8
0
def fib_seq(offset=0):
    track = Track(instrument=Piano())

    stop_at = 60
    i = 1
    f = 1
    while f < stop_at:
        f = fib(i) + offset
        ni = f % 12
        octave = (f / 12) + 1
        note = notes.int_to_note(ni)
        track.add_notes('%s-%d'%(note, octave), 4)

        i += 1
    return track
Пример #9
0
def NewTrack(beats, count, withChromatics, with16):
    """
    NewTrack(liczba_uderzeń_w_takcie, liczba_taktów, czy_z_chromatyką, czy_z_16)
    zwraca krotkę z trackiem i liczbą nut
    """
    track = Track(Instrument())
    rhythms = []
    noOfNotes = 0
    melodyCount = 0

    for ii in range(count):
        rhythms.append(newBarRhythm(beats, with16))
        noOfNotes += len(rhythms[ii])

    if withChromatics:
        melody = newMelody(noOfNotes)
    else:
        melody = newMelodyWithoutChromatics(noOfNotes)

    for rhythm in rhythms:
        b = Bar("C", (beats, 4))
        for note in rhythm:
            k = random.random()
            if k > pOfRests:
                b.place_notes(melody[melodyCount], 4 / note)
            else:
                b.place_notes(None, 4 / note)
            melodyCount += 1
        track + b
    return (track, melodyCount)
Пример #10
0
    def play(self, melody, chords, bpm, scores, bars, key, mode, modeToPass,
             tra, file, out_dir):
        t2 = Track()
        sh = progressions.to_chords(chords, key)
        for i in range(0, len(sh)):
            b = Bar(None, (4, 4))
            if len(chords[i][0]) > 5:
                b.place_notes(None, 1)
            else:
                b.place_notes(NoteContainer(sh[i]), 1)
            t2 + b
        fluidsynth.pan(1, 25)
        fluidsynth.pan(2, 120)
        fluidsynth.main_volume(2, 50)
        fluidsynth.play_Tracks([melody, t2], [1, 2], bpm)

        # sleep(500000)

        button = Button(text='Clique para rearmonizar!',
                        command=lambda: self.checkReharmonize(
                            chords, scores, bars, key, mode, modeToPass, tra,
                            bpm, file, out_dir),
                        bg='brown',
                        fg='white',
                        font=('helvetica', 9, 'bold'))
        self.canvas1.create_window(200, 250, window=button)
Пример #11
0
    def get_track(self, dict):
        """
        parse track from matrix representation
        :param dict: mapping of beats to notes that occurred on that particular beat
        :param length:
        :return:
        """

        track = Track()
        for key in sorted(dict.iterkeys()):
            notes = dict[key]
            mingus = []
            for chord in notes:
                mingus.append(chord[0])
            track.add_notes(mingus)
        return track
Пример #12
0
def track_creator(instrument_name, channel):
    instrument = MidiInstrument()
    track = Track(instrument, channel=channel)
    instrument.name = instrument_name
    track.instrument.instrument_nr = MidiInstrument.names.index(
        instrument_name)
    return track
Пример #13
0
def init_random_track(key, is_subject=True):
    notes = keys.get_notes(key)
    bar = Bar(key=key)
    while bar.current_beat < 1:
        # Randomize pitch and duration of each note.
        duration = 2**random.randint(1, 3)
        pitch = notes[random.randint(0, 6)]

        # If it is intened to be a subject, set the first note to the root.
        if bar.current_beat == 0 and is_subject == True:
            pitch = notes[0]

        # If the randomized duration doesn't fit in the bar, make it fit
        if 1 / duration > 1 - bar.current_beat:
            duration = 1 / (1 - bar.current_beat)

        # Place the new note in the bar
        bar.place_notes(pitch, duration)

    # Create a track to contain the randomized bar
    track = Track()
    track + bar

    # Return the track
    return track
Пример #14
0
 def __init__(self):
     self.instrument = "Electric Piano 1"
     self.tempo = 120.0
     self.notes = Track()
     self.length = 16
     self.key = "C"
     self.raw_song = []
     self.weights = None
Пример #15
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
Пример #16
0
def convert_pattern_to_mingus_track(ctx, patterns):
    result = Track()
    result.instrument = MidiPercussionInstrument()
    for pattern in patterns:
        resolution = pattern.attributes["resolution"]
        for tick in pattern.get_ticks():
            placed = result.add_notes(tick.notes, resolution)
            if not placed:
                result.bars[-1].current_beat = result.bars[-1].length
                max_length = result.bars[-1].length - \
                        result.bars[-1].current_beat 
                if max_length == 0.0:
                    print "wut"
                    continue
                else:
                    print result.add_notes(tick.notes, 1.0 / max_length)
                    print max_length, 1.0 / max_length, resolution, result.bars[-1].current_beat +  max_length
    return result
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
Пример #18
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
Пример #19
0
def playTrack(arr):
	fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa")
	SF2 = '/usr/share/sounds/sf2/FluidR3_GM.sf2'
	if not fluidsynth.init(SF2):
		print "Couldn't load soundfont", SF2
		sys.exit(1)
	t = Track()
	for note in arr:
		t + note
	fluidsynth.play_Track(t,1)
Пример #20
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
Пример #21
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
Пример #22
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
Пример #23
0
Файл: song.py Проект: tewe/canta
    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]
Пример #24
0
def generate_track(g, n, name):
    root = np.random.randint(0, n)
    edges = nx.bfs_edges(g.G, root)
    nodes = [root] + [v for u, v in edges]
    m = MidiInstrument(4)
    t = Track()
    track = []
    t.instrument = m
    nNotes = 0
    print("##### Creating Tracks")
    for x in nodes:
        value = t.add_notes(NoteContainer(g.G.nodes[x]["note"]),
                            g.G.nodes[x]["duration"])
        t.bars[-1].set_meter((n, 1))
        track.append(g.G.nodes[x]["note"])
        nNotes = nNotes + 1
    print("##### Notes Generated:")
    print(*t)
    print("##### Number of notes:")
    print(nNotes)
    midi_file_out.write_Track(name + ".mid", t)
    return t
Пример #25
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)
Пример #26
0
class Song:
    instrument = "Electric Piano 1"  #instrument
    tempo = 120.0  #tempo in beats per minute
    notes = Track()  #Actual sequence of Notes (defined above)
    weights = None
    length = 16  #number of bars in the song
    key = "C"  #key of the song
    raw_song = []  #the song as a simple list of note/duration pairs

    def __init__(self):
        self.instrument = "Electric Piano 1"
        self.tempo = 120.0
        self.notes = Track()
        self.length = 16
        self.key = "C"
        self.raw_song = []
        self.weights = None
Пример #27
0
 def write_mingus(self, outfile):
     notes = list(self.timeseries['Notes'])
     t = Track()
     for n in range(len(notes)):
         if n % 4 == 0:
             b = Bar(self.key, (4, 4))
         if notes[n] != 'Z':
             b + notes[n]
         else:
             b + None
         if (n + 1) % 4 == 0:
             t + b
     self.composition + t
     self.track = t
     lily_composition = LilyPond.from_Composition(self.composition)
     print lily_composition
     LilyPond.to_pdf(lily_composition, outfile)
Пример #28
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)
Пример #29
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
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
Пример #31
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
Пример #32
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
Пример #33
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)
Пример #34
0
 def __init__(self):
     self.track = Track()
Пример #35
0
tr = lambda note: chords.triad(note, "C")

# 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)
Пример #36
0
cymbalpercussion = []
tompercussion = []
major_chords = [
    simple_chordI, simple_chordIV, simple_chordV, simple_chordIi,
    complex_chordI, complex_chordIV, complex_chordV, complex_chordIi
]
minor_chords = [
    simple_chordII, simple_chordIII, simple_chordVI, simple_chordV7,
    complex_chordII, complex_chordIII, complex_chordVI, complex_chordV7
]
left_hand_music = []
right_hand_list = []
right_hand_music = []
downbeatbar = Bar()
righthandbar = Bar()
synthtrack1 = Track()
synthtrack1.instrument = synth
electricguitartrack1 = Track()
electricguitartrack1.instrument = electricguitar
brasstrack1 = Track()
brasstrack1.instrument = brass
bassetrack1 = Track()
bassetrack1.instrument = basse
strintrack1 = Track()
strintrack1.instrument = string
guitartrack1 = Track()
guitartrack1.instrument = guitar
frhorntrack1 = Track()
frhorntrack1.instrument = frhorn
righthandtrack1 = Track()
righthandtrack1.instrument = brightpiano
Пример #37
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
Пример #38
0
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        if header[2]['fps']:
            print("Don't know how to parse this yet")
            return c
        ticks_per_beat = header[2]['ticks_per_beat']
        for track in track_data:
            t = Track()
            b = Bar()
            metronome = 1  # Tick once every quarter note
            thirtyseconds = 8  # 8 thirtyseconds in a quarter note
            meter = (4, 4)
            key = 'C'
            for e in track:
                (deltatime, event) = e
                duration = float(deltatime) / (ticks_per_beat * 4.0)
                if duration != 0.0:
                    duration = 1.0 / duration
                if deltatime != 0:
                    if not b.place_notes(NoteContainer(), duration):
                        t + b
                        b = Bar(key, meter)
                        b.place_notes(NoteContainer(), duration)

                if event['event'] == 8:
                    if deltatime == 0:
                        pass
                elif event['event'] == 9:

                # note on

                    n = Note(notes.int_to_note(event['param1'] % 12),
                             event['param1'] / 12 - 1)
                    n.channel = event['channel']
                    n.velocity = event['param2']
                    if len(b.bar) > 0:
                        b.bar[-1][2] + n
                    else:
                        b + n
                elif event['event'] == 10:

                # note aftertouch

                    pass
                elif event['event'] == 11:

                # controller select

                    pass
                elif event['event'] == 12:

                # program change

                    i = MidiInstrument()
                    i.instrument_nr = event['param1']
                    t.instrument = i
                elif event['event'] == 0x0f:

                # meta event Text

                    if event['meta_event'] == 1:
                        pass
                    elif event['meta_event'] == 3:

                    # Track name

                        t.name = event['data']
                    elif event['meta_event'] == 6:

                    # Marker

                        pass
                    elif event['meta_event'] == 7:

                    # Cue Point

                        pass
                    elif event['meta_event'] == 47:

                    # End of Track

                        pass
                    elif event['meta_event'] == 81:

                    # Set tempo warning Only the last change in bpm will get
                    # saved currently

                        mpqn = self.bytes_to_int(event['data'])
                        bpm = 60000000 / mpqn
                    elif event['meta_event'] == 88:

                    # Time Signature

                        d = event['data']
                        thirtyseconds = self.bytes_to_int(d[3])
                        metronome = self.bytes_to_int(d[2]) / 24.0
                        denom = 2 ** self.bytes_to_int(d[1])
                        numer = self.bytes_to_int(d[0])
                        meter = (numer, denom)
                        b.set_meter(meter)
                    elif event['meta_event'] == 89:

                    # Key Signature

                        d = event['data']
                        sharps = self.bytes_to_int(d[0])
                        minor = self.bytes_to_int(d[0])
                        if minor:
                            key = 'A'
                        else:
                            key = 'C'
                        for i in range(abs(sharps)):
                            if sharps < 0:
                                key = intervals.major_fourth(key)
                            else:
                                key = intervals.major_fifth(key)
                        b.key = Note(key)
                    else:
                        print('Unsupported META event', event['meta_event'])
                else:
                    print('Unsupported MIDI event', event)
            t + b
            c.tracks.append(t)
        return (c, bpm)
    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)
Пример #40
0
	def MIDI_to_Composition(self, file):
		header, track_data = self.parse_midi_file(file)

		c = Composition()
		if header[2]["fps"]:
			print "Don't know how to parse this yet"
			return c

		ticks_per_beat = header[2]["ticks_per_beat"]
		for track in track_data:
			t = Track()
			b = Bar()
			metronome = 1 # Tick once every quarter note
			thirtyseconds = 8 # 8 thirtyseconds in a quarter note
			meter = (4,4)
			key = 'C'

			for e in track:

				deltatime, event = e
				duration =  float(deltatime) / (ticks_per_beat * 4.0)
				if duration != 0.0:
					duration = 1.0 / duration

				if deltatime != 0:
					if not b.place_notes(NoteContainer(), duration):
						t + b
						b = Bar(key, meter)
						b.place_notes(NoteContainer(), duration)
						

				# note off
				if event["event"] == 8:
					if deltatime == 0:
						pass

				# note on 
				elif event["event"] == 9:
					n = Note(notes.int_to_note(event["param1"] % 12), 
						event["param1"] / 12 - 1)
					n.channel = event["channel"]
					n.velocity = event["param2"]

					if len(b.bar) > 0:
						b.bar[-1][2] + n
					else:
						b + n

				# note aftertouch
				elif event["event"] == 10:
					pass
				# controller select
				elif event["event"] == 11:
					pass
				# program change
				elif event["event"] == 12:
					i = MidiInstrument()
					i.instrument_nr = event["param1"]
					t.instrument = i

				# meta event
				elif event["event"] == 15:

					# Track name
					if event["meta_event"] == 3:
						t.name = event["data"]
					
					# Marker 
					elif event["meta_event"] == 6:
						pass

					# Cue Point
					elif event["meta_event"] == 7:
						pass

					# End of Track
					elif event["meta_event"] == 47:
						pass

					# Set tempo 
					#warning Only the last change in bpm will get saved currently
					elif event["meta_event"] == 81:
						mpqn = self.bytes_to_int(event["data"])
						bpm = 60000000 / mpqn

					# Time Signature
					elif event["meta_event"] == 88:
						d = event["data"]
						thirtyseconds = self.bytes_to_int(d[3])
						metronome = self.bytes_to_int(d[2]) / 24.0
						denom = 2 ** self.bytes_to_int(d[1])
						numer = self.bytes_to_int(d[0])
						meter = (numer, denom)
						b.set_meter(meter)

					# Key Signature
					elif event["meta_event"] == 89:
						pass

					else:
						print "Unsupported META event", event["meta_event"]

				else:
					print "Unsupported MIDI event", event

			t + b
			c.tracks.append(t)
		
		return c, bpm
Пример #41
0
"""
Three canti firmi from the "Composition in Simple Counterpoint" on p128 of the Sophomore Music manual.
To be used in counterpoint stuff.
"""

from mingus.containers import Track

first = Track()
for note in ('D', 'A', 'Bb', 'A', 'G', 'D', 'F', 'E', 'D'):
    first.add_notes(note, 1)
    # current_beat attribute is currently 0.0 for all of these notes - do they play simultaneously?

second = Track()
for note in ('E-4', 'A-3', 'A-4', 'G-4', 'F-4', 'E-4', 'D-4', 'F-4', 'E-4'):
    second.add_notes(note, 1)

third = Track()
for note in ('C', 'G', 'A', 'B', 'C', 'D', 'E', 'D', 'C'):
    third.add_notes(note, 1)

closer = Track()
for note in ('D', 'D', 'E', 'F#', 'F#', 'F#', 'G', 'A',
             'A', 'A', 'B', 'B', 'A', 'rest', 'rest', 'rest',
             'A', 'A', 'G', 'F#', 'G', 'G', 'F#', 'E',
             'D', 'D', 'E', 'C#', 'D', 'rest', 'rest', 'rest'):
    closer.add_notes(note, 1)

# rests need to be placed separately in mingus?? maybe forking them is a good idea at this point

print first
print second
Пример #42
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
Пример #43
0
from mingus.core import chords, intervals, notes, scales 
from mingus.containers import Note, NoteContainer, Bar, Track, Composition
from mingus.containers.Instrument import MidiInstrument
from mingus.midi import MidiFileOut
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
Пример #44
0
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        if header[2]['fps']:
            print "Don't know how to parse this yet"
            return c
        ticks_per_beat = header[2]['ticks_per_beat']

        for track in track_data:
            # this loop will gather data for all notes,
            # set up keys and time signatures for all bars
            # and set the tempo and instrument for the track.

            metronome = 1  # Tick once every quarter note
            thirtyseconds = 8  # 8 thirtyseconds in a quarter note
            step = 256.0 # WARNING: Assumes our smallest desired quantization step is a 256th note.

            meter = (4, 4)
            key = 'C'
            bar = 0
            beat = 0
            now = (bar, beat)
            b = None

            started_notes = {}
            finished_notes = {}
            b = Bar(key=key, meter=meter)
            bars = [b]

            bpm = None
            instrument = None
            track_name = None

            for deltatime, event in track:
                if deltatime != 0:
                    duration = (ticks_per_beat * 4.0) / float(deltatime)

                    dur_q = int(round(step/duration))
                    length_q = int(b.length * step)

                    o_bar = bar
                    c_beat = beat + dur_q
                    bar += int(c_beat / length_q)
                    beat = c_beat % length_q

                    while o_bar < bar:
                        o_bar += 1
                        o_key = b.key
                        b = Bar(key=key, meter=meter)
                        b.key = o_key
                        bars.append(b)

                    now = (bar, beat)

                if event['event'] == 8:
                # note off
                    channel = event['channel']
                    note_int = event['param1']
                    velocity = event['param2']
                    note_name = notes.int_to_note(note_int % 12)
                    octave = note_int / 12 - 1

                    note = Note(note_name, octave)
                    note.channel = channel
                    note.velocity = velocity

                    x = (channel, note_int)
                    start_time = started_notes[x]
                    del started_notes[x]
                    end_time = now

                    y = (start_time, end_time)
                    if y not in finished_notes:
                        finished_notes[y] = []

                    finished_notes[y].append(note)

                elif event['event'] == 9:
                # note on
                    channel = event['channel']
                    note_int = event['param1']
                    velocity = event['param2']
                    x = (channel, note_int)

                    # add the note to the current NoteContainer
                    started_notes[x] = now

                elif event['event'] == 10:
                # note aftertouch
                    pass

                elif event['event'] == 11:
                # controller select
                    pass

                elif event['event'] == 12:
                # program change
                # WARNING: only the last change in instrument will get saved.
                    i = MidiInstrument()
                    i.instrument_nr = event['param1']
                    instrument = i

                elif event['event'] == 0x0f:
                # meta event Text
                    if event['meta_event'] == 1:
                        pass

                    elif event['meta_event'] == 3:
                    # Track name
                        track_name = event['data']

                    elif event['meta_event'] == 6:
                    # Marker
                        pass

                    elif event['meta_event'] == 7:
                    # Cue Point
                        pass

                    elif event['meta_event'] == 47:
                    # End of Track
                        pass

                    elif event['meta_event'] == 81:
                    # Set tempo
                    # WARNING: Only the last change in bpm will get saved
                        mpqn = self.bytes_to_int(event['data'])
                        bpm_o = bpm
                        bpm = 60000000 / mpqn

                    elif event['meta_event'] == 88:
                    # Time Signature
                        d = event['data']
                        thirtyseconds = self.bytes_to_int(d[3])
                        metronome = self.bytes_to_int(d[2]) / 24.0
                        denom = 2 ** self.bytes_to_int(d[1])
                        numer = self.bytes_to_int(d[0])
                        meter = (numer, denom)
                        b.set_meter(meter)

                    elif event['meta_event'] == 89:
                    # Key Signature
                        d = event['data']
                        sharps = self.bytes_to_int(d[0])
                        minor = self.bytes_to_int(d[0])
                        if minor:
                            key = 'A'
                        else:
                            key = 'C'
                        for i in xrange(abs(sharps)):
                            if sharps < 0:
                                key = intervals.major_fourth(key)
                            else:
                                key = intervals.major_fifth(key)
                        b.key = Note(key)

                    else:
                        print 'Unsupported META event', event['meta_event']

                else:
                    print 'Unsupported MIDI event', event

            t = Track(instrument)
            t.name = track_name

            sorted_notes = {}

            # sort the notes (so they are added to the bars in order)
            # this loop will also split up notes that span more than one bar.
            for x in finished_notes:
                (start_bar, start_beat), (end_bar, end_beat) = x
                if end_beat == 0:
                    end_bar -= 1
                    end_beat = int(bars[end_bar].length * step)

                while start_bar <= end_bar:
                    nc = NoteContainer(finished_notes[x])
                    b = bars[start_bar]

                    if start_bar < end_bar:
                        # only executes when note spans more than one bar.
                        length_q = int(b.length * step)
                        dur = int(step/(length_q - start_beat))
                    else:
                        # always executes - add the final section of this note.
                        dur = int(step/(end_beat-start_beat))

                    if start_beat != 0:
                        at = float(start_beat)/step
                    else:
                        at = 0.0

                    if start_bar not in sorted_notes:
                        sorted_notes[start_bar] = {}
                    if at not in sorted_notes[start_bar]:
                        sorted_notes[start_bar][at] = (dur, nc)

                    # set our offsets for the next loop
                    start_beat = 0
                    start_bar += 1

            # add all notes to all bars in order.
            for start_bar in sorted(sorted_notes.keys()):
                for at in sorted(sorted_notes[start_bar].keys()):
                    dur, nc = sorted_notes[start_bar][at]
                    bars[start_bar].place_notes_at(nc, dur, at)

            # add the bars to the track, in order
            for b in bars:
                b.fill_with_rests()
                t + b

            # add the track to the composition
            c.tracks.append(t)

        return (c, bpm)
Пример #45
0
	You should specify the SF2 soundfont file.

"""

from mingus.core import progressions, intervals
from mingus.core import chords as ch
from mingus.containers import NoteContainer, Note, Track
from mingus.midi.MidiFileOut import write_Track
import time, sys
from random import random

def strip_chords(l):
	# une fonction pour ne garder que la fondamentale
	# d'un accord, sinon mingus nous le joue en arpeggié
	ret = []
	for e in l:
		ret.append(e[0])
	return ret

progression = ["I", "vi", "iv", "V7"]
key = 'C'

chords = progressions.to_chords(progression, key)
notes = strip_chords(chords)
tr = Track()
for note in notes:
	tr.add_notes(note, duration=1)

write_Track('out.mid', tr)
Пример #46
0
class BassInstrument(Instrument):
	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)
Пример #47
0
c.augment()  #升半音
c.diminish()  #降半音
c.remove_redundant_accidentals()  #清理多余升降号(只能成对清理,烂)

#谱容器
from mingus.containers import NoteContainer
#创建谱容器对象(继承列表,完全可以按列表操作,不用看下面的)
n = NoteContainer(['A-3', 'C-5', 'B-4'])
n.add_note('F-1')  # 0位加音
n.remove_note('B', 4)  #删音
n.empty()  #清空

#乐器音色
from mingus.containers.instrument import Instrument, Piano, Guitar
#创建乐器对象
i = Instrument()
i.range  #乐器音域
i.set_range((Note('C-2'), Note('E-4')))  #设定音域
i.note_in_range('F-4')  #判断音是否在乐器音域内
#音轨
from mingus.containers import Track
t = Track(i)  #乐器放入音轨容器

#MIDI音乐播放(安装困难)
#from mingus.midi import fluidsynth
#fluidsynth.init("soundfont.SF2")
#fluidsynth.play_Note( Note('C-5') )

from mingus.midi import MidiFileOut
MidiFileOut.write_NoteContainer('test.mid', n)
Пример #48
0
import time
PATH_SOUNDFONT = "./TimGM6mb.sf2"

from mingus.midi import fluidsynth
fluidsynth.init(PATH_SOUNDFONT, "pulseaudio")
time.sleep(1)

from mingus.containers import Note, Track
#fluidsynth.play_Note(Note("C-5"))

track = Track()
track.add_notes(["A-5", "D-5"], 2)
track.add_notes(["B-5", "E-5"], 2)

fluidsynth.play_Track(track)

time.sleep(5)