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!")
Beispiel #2
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
Beispiel #3
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
    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
Beispiel #5
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
Beispiel #6
0
def reverse(track, key='C'):
    # Copy value of reference to aviod problems with overwriting
    input_track = copy.deepcopy(track)
    #empty track to write to later
    reversed_track = Track()
    b = Bar(key)
    reversed_track.add_bar(b)

    #create a reversed list of notes from input track
    input_notes = input_track.get_notes()
    reversed_notes = reversed(list(input_notes))

    #Add notes to reversed_track
    for note in reversed_notes:
        reversed_track.add_notes(note[-1], duration=note[1])

    # Return reversed track
    return reversed_track
Beispiel #7
0
def 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
def createMingusComposition(intermed, timesig, bIsTreble, bSharps):
	comp = Composition()
	comp.set_title('Trilled Results')
	comp.set_author('Author')
	if bIsTreble: ins = TrebleInstrument('')
	else: ins=BassInstrument('')
	
	track = Track(ins)
	track.name = 'Part 1'
	comp.add_track(track)

	assert len(timesig)==2 and isinstance(timesig[0],int) and isinstance(timesig[1],int)
	firstbar = Bar(meter=timesig)
	track.add_bar(firstbar)
	
	mapDurs={ 
		int(intermed.baseDivisions*4): 1.0, #whole note,
		int(intermed.baseDivisions*2): 2.0, #half note
		int(intermed.baseDivisions*1): 4.0, #qtr note, and so on
		int(intermed.baseDivisions*0.5): 8.0,
		int(intermed.baseDivisions*0.25): 16.0,
		int(intermed.baseDivisions*0.125): 32.0,
		int(intermed.baseDivisions*0.0625): 64.0,
			}
	
	for note in intermed.noteList:
		if note.pitch==0 or note.pitch==(0,): # a rest
			thepitches = tuple()
		else: # a note
			thepitches = []
			for pitch in note.pitch:
				pname, poctave = music_util.noteToName(pitch,bSharps)
				thepitches.append(pname+'-'+str(poctave))
		
		dur = note.end - note.start
		if dur not in mapDurs: raise NotesinterpretException('Unknown duration:' + str(dur))
		notecontainer = NoteContainer(thepitches)
		notecontainer.tied =  note.isTied
		bFit = track.add_notes(notecontainer, mapDurs[dur])
		assert bFit
	
		#note that, naturally, will enforce having correct measure lines, since going across barline throughs exception
	
	return comp
Beispiel #10
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
Beispiel #11
0
def main():
    misty_numerals = 'IM7, v-7, I7, IVM7, iv-9, bVII7, IM7, vi-7, ii-7, V7, iii-7, VI7, ii-7, V7, \
        IM7, v-7, I7, IVM7, iv-9, bVII7, IM7, vi-7, ii-7, V7, I6, bVII9, IM7, \
        v-7, I7b9, IVM7, IVM7,\
        bv-7, VII7, II7, iii-7, VI7b9, ii-7, V7, \
        IM7, v-7, I7, IVM7, iv-9, bVII7, IM7, vi-7, ii-7, V7, I6, I6'

    misty_durs = [
        1, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 2,
        2, 2, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 1, 2, 2, 2, 2, 1, 1,
        1, 1
    ]

    mistyChart = sidewinder.Chart(progression=misty_numerals, key='F')
    mistyChart.set_durations(durations=misty_durs)

    twofiveone = ['IIm7', 'V7', 'IM7']
    two_five_ones = detect_numeral_pattern(
        mistyChart.get_numeral_representation(),
        pattern=twofiveone,
        transposing='True',
        original_key=mistyChart.key)
    print(two_five_ones)

    tfo_durs = [[
        mistyChart.durations[tf['start_index']],
        mistyChart.durations[tf['start_index'] + 1],
        mistyChart.durations[tf['start_index'] + 2]
    ] for tf in two_five_ones['hits']]

    # from random import choices
    # # asc = [1,2,3,4,5,4,3,1]
    # asc = [1,2,4,'b7','b9']
    # p = choices(asc, weights=[1,2,2,2,1], k=32)
    # print(p)
    # melody = get_scale_patterns('chromatic', p=p, keys=['F'], pattern_as_chromatic=True)
    # print(melody['F'][0])

    # add a selection of melody to a selection of bars in the Composition

    arps = [[from_shorthand(chord)[i] for i in (0, 1, 2, 3, 2, 1, 0, 1)]
            for chord in mistyChart.progressionShorthandList]
    notes_ = []
    note_durations = []
    for arp, chord_dur in zip(arps, mistyChart.durations):
        if chord_dur == 1:
            note_durations += [8 for _ in range(8)]
            notes_ += [arp[i] for i in range(8)]
        elif chord_dur == 2:
            note_durations += [8 for _ in range(4)]
            notes_ += [arp[i] for i in range(4)]
    assert len(notes_) == len(note_durations)

    t = Track()
    for i, _ in enumerate(note_durations):
        t.add_notes(notes_[i], note_durations[i])

    # use the db to add/overlay a 251 lick in the right place
    start_index = two_five_ones['hits'][0][
        'start_index']  # refers to index in chord progression (not bar)
    key = two_five_ones['hits'][0]['key']
    durs = tfo_durs[0]  # [1,1,1]

    # chords_ = mistyChart.progressionShorthandList[start_index:start_index+len(twofiveone)]
    ### now search db for a 251 in F w/ duratons 1,1,1 then place at start_index
    db = TinyDB(
        r'C:\Users\Sam\Documents\Sidewinder\local files\jazz-licks-db-260720-new.json'
    )  # set-up / connection
    # candidate_licks = find_partial_matches(db, {'tags':'251'}) # gives db id's (doc_id) # searching should be better, done on actual chord metadata
    candidate_licks = find_by_chords_durations(db,
                                               chords=['Gm7', 'C7', 'FM7'],
                                               durations=[1, 1, 1])

    # candidate_licks = [load_entry(db, doc_id) for doc_id in candidate_licks] # instantiate from db
    lick251 = load_entry(db, candidate_licks[0])

    # for doc_id in candidate_licks[-15:]:
    #     print(db.get(doc_id=doc_id))
    # print(candidate_licks[0].chords)
    # candidate_licks[0].to_midi()

    notes_ = [nc[2] for bar in lick251.passage for nc in bar]
    notes_ = [nc[0] if bool(nc) else None for nc in notes_]
    durations_ = [nc[1] for bar in lick251.passage for nc in bar]

    # [start of Misty ... 251 lick notes_,durations_ ... rest of Misty]
    start_bar = 8  # could compute using start_index and misty_durs
    t2 = Track_from_list(t[:start_bar - 1])
    for n, d in zip(notes_, durations_):
        t2.add_notes(n, d)
    for bar in Track_from_list(
            t[start_bar - 1 + 4:]
    ):  # known that the lick is 4 bars, could probably compute from lick251.passage
        t2 + bar

    track_to_midi(t2, name='midi_out\\test251_lick_add')
Beispiel #12
0
def merge_tracks(track1, track2):
    merged_track = Track()
    #Copy inputs to prevent overwriting
    track1_notes = copy.deepcopy(track1).get_notes()
    track2_notes = copy.deepcopy(track2).get_notes()

    #Bool that indicates if we should read in the next note in track2
    next_note2 = True

    for note1 in track1_notes:
        #Bool that indicates if we should read in the next note in track1
        next_note1 = False

        #If we want to read in the next note in track 2 attempt to do so
        if next_note2:
            try:
                note2 = next(track2_notes)
            #If generator is empty(we have already added all notes from track 2) just add the next note from track1
            except StopIteration:
                merge_tracks.add_notes(note1[-1], note1[1])
                continue

        #While loop to check if we have added the current note1
        while (not next_note1):
            #In this part we compare the current note from track1 (note1) and current node from track2(note2)

            #If notes start at the same time
            if note1[0] == note1[0]:
                #Determine the added notecontainer value, if any of the notes is a oause add the value of the other note
                if note1[-1] is None:
                    nc = note2[-1]
                elif note2[-1] is None:
                    nc = note1[-1]
                else:
                    nc = note1[-1] + note2[-1]

                # if the notes have different length always use the shortest one
                if note1[1] > note2[1]:
                    merged_track.add_notes(nc, note2[1])
                else:
                    merged_track.add_notes(nc, note1[1])

                next_note1 = True  #read in next note from track1
                next_note2 = True  #read in next note from track2

            #If note1 starts before note2
            elif note1[0] < note2[0]:
                #Determine time until next note in track2
                time_to_next = int(1.0 / (note2[0] - note1[0]))

                #If length of note1 is bigger than time until next note in track2 then cut lenght to fit
                if note1[1] > time_to_next:
                    merged_track.add_notes(nc, time_to_next)

                #Otherwise add note as normal
                else:
                    merged_track.add_notes(nc, note1[1])

                next_note1 = True  #read in next note from track1
                next_note2 = False  #do not read in next note from track2

            #If note2 starts before note1
            else:
                #If length of note2 is bigger than time until next note in track1 then cut lenght to fit
                temp = int(1.0 / (note1[0] - note2[0]))
                if note2[1] > temp:
                    merged_track.add_notes(nc, temp)
                else:
                    merged_track.add_notes(nc, note2[1])

                next_note2 = True  #read in next note from track2
                #do not read in next note from track1 (default)

    #Add remaining notes if any from track2
    for note2 in track2_notes:
        merged_track.add_notes(note2[-1], note2[1])

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

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

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

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

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

    if num == "panther":  #Scale E
        track.add_notes('D#-4', 8)
        track.add_notes('E-4', 8 / 3)
        track.add_notes('F#-4', 8)
        track.add_notes('G-4', 8 / 3)
    return track
class PianoPlayer:
    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

    def addTrack(self, notes, duration=None):
        """
        function to update track
        :param notes: array of notes to add
        :param duration: how long note should play for
        :return: none
        """
        mingus_notes = []
        for n in notes:
            if isinstance(n, int) == True:
                x = Note().from_int(n)
                mingus_notes.append(x)
            else:
                x = Note(n)
                mingus_notes.append(x)
        self.track.add_notes(mingus_notes, duration=duration)

    def clearTrack(self):
        """
        function to reset track and matrix
        :return: none
        """
        self.track = Track(Piano())

    def saveTrack(self, filename):
        """
        save track in piano class to file
        :param filename: name of file
        :return: none
        """
        track = self.track
        path = "static/library/"
        file = path + filename + ".mid"
        midi_file_out.write_Track(file, track)

    def saveComposition(self, filename, track):
        """
        function to save customized composition to file
        :param filename: name of file
        :param track: Track() object to save
        :return: none
        """
        path = "static/library/"
        file = path + filename + ".mid"
        midi_file_out.write_Track(file, track)

    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

    def add_file(self, filename):
        """
        function to add file to matrix
        :param filename: name if midi file
        :return: matrix and array of beats (each beat is a 16th note)
        """
        file = midi_file_in.MIDI_to_Composition(filename)

        #get total count
        count = []
        i = -1
        for bar in file[0][0]:
            for info in bar:
                if (info[0] == 0):
                    i = i + 1
                count.append(info[0] + i)
        #normalize count array
        count_total = []
        for i in range(0, len(count) * 4):
            count_total.append(0.0625 * i)
        matrix = self.midi_matrix(track=file[0][0],
                                  total_count=len(count_total))
        #count.pop()
        return (matrix, count_total)

    def midi_matrix(self, track, total_count=6):
        """
        build matrix where columns = notes and rows = beats
        - one denotes that a note occured on a particular beat
        :param track: Track() object to be parsed
        :param total_count: array of beats (16th notes)
        :return: matrix
        """
        matrix = {}
        for n in self.notes:
            i = int(n)
            matrix[i] = [0] * total_count
        count = 0
        for bar in track:
            for info in bar:
                for n in info[2]:
                    i = int(n) + 12
                    x = matrix[i]

                    x[count * 4] = 1
                    matrix[i] = x
                count = count + 1
        return matrix

    def getMatrix(self):
        """
        function to get matrix from class
        :return: matrix
        """
        return self.matrix

    def getNotes(self):
        """
        function to get array of notes
        :return: notes
        """
        temp = self.notes
        temp.reverse()
        return temp[0:len(temp) - 11 - 1]

    def make_queue(self, filename):
        """
        parse a song into a composition for play along feature
        :param filename: name of midi file
        :return: return an array of notes in file
        """
        file = midi_file_in.MIDI_to_Composition(filename)

        composition = self.buildComposition(file[0])
        result = []
        for track in composition[0]:

            for bar in track:
                for notes in bar:
                    temp = []
                    for n in notes[2]:
                        temp.append(int(n))
                    if len(notes[2]) > 0:
                        result.append(temp)
        return result

    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

    def get_composition(self, composition, tempo, length):
        """

        :param composition: matrix of midi file to be parsed
        :param tempo: tempo of piece
        :param length: number of beats in piece
        :return: track
        """
        whole = tempo * 4
        half = tempo * 2
        quarter = tempo
        eighth = tempo / 2
        sixteenth = tempo / 4
        duration_dict = {
            whole: 1,
            half: 2,
            quarter: 4,
            eighth: 8,
            sixteenth: 16
        }

        composition_dict = {}

        for track in composition:
            for bar in track:
                n = note_converter(str(bar['key']))
                dur = duration_dict[int(bar['duration'])]
                count = ((float(bar['clock'])) - 32) / (128 * 4)
                if count not in composition_dict:
                    temp = []
                    temp.append((Note(n), dur))
                    composition_dict[count] = temp
                else:
                    x = composition_dict[count]
                    x.append((Note(n), dur))
                    composition_dict[count] = x
                    # extract note
                    # n.append(str(i))\
            #c.add_track(t)
        track = self.get_track(dict=composition_dict)
        return track
Beispiel #16
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)
        if i[0] == "E":
            var2 += "3"
        if i[0] == "F":
            var2 += "4"
        if i[0] == "G":
            var2 += "5"
        if i[0] == "A":
            var2 += "6"
        if i[0] == "B":
            var2 += "7"
    return var2
for i in right_hand_music:
    if i[2] == "None":
        right_hand_list.append([i[2],i[1]])
        if first_time:
            lefthandtrack.add_notes(None,4)
        first_time = False
    else:
        right_hand_list.append([i[2],i[1]])
        if math.floor(i[0]/2) == i[0]/2:
            left_hand_music.append(i[2])
            first_time = False
            if i[1] > 2:
                if math.floor((i[0] + i[1]) / 2) > math.floor(i[0] / 2):
                    left_hand_music.append(i[2])
        else:
            if math.floor((i[0]+i[1])/2) > math.floor(i[0]/2):
                if i[1] >= 3:
                    first_time = False
                    left_hand_music.append(i[2])
                else:
Beispiel #18
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
Beispiel #19
0
		self.name = name
		Instrument.__init__(self)

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

ins = TrebleInstrument('kazoo')

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

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

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

s = MusicXML.from_Composition(comp)
f=open('out.xml','w')
from mingus.midi import fluidsynth, midi_file_out
from mingus.midi.fluidsynth import FluidSynthSequencer
from mingus.containers import Bar, Track, Composition
from mingus.containers.instrument import MidiInstrument
from midi2audio import FluidSynth

ins = MidiInstrument()
ins.instrument_nr = 1
player = FluidSynthSequencer()
fluidsynth.init('Timbre.sf2', player)
t = Track()
t.add_notes("C-3", 4)
t.instrument = ins
midi_file_out.write_Track('instrumenttest1.mid', t, bpm=500)
FluidSynth("Timbre.sf2").midi_to_audio('instrumenttest1.mid',
                                       'instrumenttest1.wav')
Beispiel #21
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
print third
Beispiel #22
0
def temporal_realign_track_bars(track, pickup=None, give_notes=False, give_durations=False, debug=False):
    '''Realign notes within bar lines (e.g. splitting rest events which cross barlines after reading in from midi)
    
    Warning: do not begin a bar with an acciacatura as current_pos will get out of sync (acciacatura implies rests and anticipation which gets confusing for timing)
    (at least in the case where the previous bar ends with a rest, not tested otherwise)'''
    notes = [notev[2] for notev in track.get_notes()]
    durations = [notev[1] for notev in track.get_notes()]
    
    # output will get out of alignment if we start mid-bar, let's workaround by padding with rests at start
    if pickup == 0: # input sanitising
        pickup = None
    if pickup is not None:
        notes = [[]] + notes
        durations = [1/pickup] + durations
    
    notes2 = []
    durations2 = []
    current_pos = 0 # maybe this should be set negative in the case of a pickup bar / upbeat ? e.g. determined by split pos
    for i, duration in enumerate(durations):
    
        # if a duration < 1.0 then we have a conjoined bar
        # e.g. a rest of duration 0.88888 is the same as 1.0 + 0.125 (i.e. whole plus quarter rest)
        # because 1/0.8888 = 1.125
        if duration < 1.0:
            ones = int(1//duration) # // gives integer part of div
            remainder = 1/duration - ones
            
            # check if we are at the end/start of a new bar
            if round(current_pos*2**10)/2**10 == current_pos//1 or round(current_pos*2**10)/2**10 == current_pos//1 + 1:  
                if debug:
                    print('splitting rest',i)
                new_durations = ones*[1.0] + [1/remainder]
            else: # if we are part way through a bar then the rem comes first
                new_durations = [1/remainder] + ones*[1.0] 
                
            notes2 += (ones+1)*[notes[i]]
            durations2 += new_durations
            current_pos += 1/durations[i]
            
        else:
            if debug:
                print(i, 'current_pos',current_pos, round(current_pos*2**10)/2**10, 1/durations[i], current_pos + 1/durations[i])
            notes2.append(notes[i])
            durations2.append(durations[i])
            current_pos += 1/durations[i]

    t = Track()
    if debug:
        t2 = Track()
        print(len(durations2), durations2)
        print(len(notes2), notes)
    for i, _ in enumerate(durations2):
        if debug:
            if not t2.add_notes(notes2[i], durations2[i]):
                print('')
                print(f'failed to add {notes2[i]}, {durations2[i]} to on index {i}')
                print(i, t2.bars[-3:])
                print('')
        t.add_notes(notes2[i], durations2[i])

    # outputs
    if give_notes and give_durations:
        return t, notes2, durations2
    elif give_notes:
        return t, notes2
    elif give_durations:
        return t, durations2
    else:
        return t
Beispiel #23
0
initialized = False
uiplayer = FluidSynthSequencer()
fluidsynth.init('goodtry.sf2', uiplayer)
cymbal = Note()
cymbal.from_int(37)
snare = Note()
snare.from_int(26)
highhat = Note()
highhat.from_int(30)
base = NoteContainer()
basenote = Note()
basenote.from_int(23)
base.add_note(basenote)
soundtrack = Track()
starttrack = Track()
starttrack.add_notes(highhat, 1)
starttrack.add_notes(highhat, 1)
starttrack.add_notes(highhat, 1)
starttrack.add_notes(highhat, 1)

for i in range(0, 32):
    if math.floor(i / 4.0) == i / 4.0:
        soundtrack.add_notes([basenote, cymbal], 1.0)
    else:
        soundtrack.add_notes(base, 1.0)
finalist2 = []
durationlist = []
downbeatlist = []
downbeatlist2 = []
downbeatlist3 = []
finallist = []
Beispiel #24
0
from mingus.containers import Composition
from mingus.containers import Track
from mingus.containers import Bar
from mingus.containers import Note, NoteContainer

from mingus.midi import midi_file_out

drum_scale = {
  "snare": Note("E", 2),
  "bass": Note("C", 2),
  "hightom": Note("B", 2),
  "midtom": Note("A", 2),
  "lowtom": Note("G", 2),
  "crash": Note("A", 3),
  "hatclosed": Note("G#", 2),
  "hatopen": Note("A#", 2),
  "ride": Note("B", 3),
  }

values = [value.quarter, value.eighth, value.sixteenth, value.triplet(value.eighth), value.triplet(value.sixteenth)]
#for i in range(0, 24):
#  bar =
drum_track = Track()

for note in drum_scale:
  drum_track.add_notes(drum_scale[note])

print(drum_track)
midi_file_out.write_Track("drum_scale.mid", drum_track)
Beispiel #25
0
from mingus.containers import Bar
from mingus.containers import Note, NoteContainer

from mingus.midi import midi_file_out

durations = [
    value.whole, value.half, value.quarter, value.eighth, value.sixteenth,
    value.triplet(value.eighth),
    value.triplet(value.sixteenth)
]

gypsy_scale = ["C", "C#", "E", "F", "G", "G#", "B", None, None]
gypsy_track = Track()

for note in gypsy_scale:
    gypsy_track.add_notes(note)

# print(gypsy_track)
# midi_file_out.write_Track("gypy_scale.mid", gypsy_track)
drums = {
    "snare": Note("E", 2),
    "kick": Note("C", 2),
    "hightom": Note("B", 2),
    "midtom": Note("A", 2),
    "lowtom": Note("G", 2),
    "crash": Note("A", 3),
    "hatclosed": Note("G#", 2),
    "hatopen": Note("A#", 2),
    "ride": Note("B", 3),
}
Beispiel #26
0
def first_voice_ending(first_track, key):
    last_bar_track = Track()
    last_bar_track.add_notes(Note(key, 4), 1)
    return last_bar_track