コード例 #1
0
ファイル: utils.py プロジェクト: doino-gretchenliev/Mid-Magic
 def createIntToNoteMap(self):
     for i in range(0, 128):
         note = i % 12;
         note_name = notes.int_to_note(note);
         octave = (i / 12) - 1;
         self.__midi_int_to_note_int_map[i] = i % 12;
         self.__midi_int_to_note_map[i] = notes.int_to_note(i % 12);
         self.__note_octave_to_midi_note_map[note_name + str(octave)] = i;
         self.__midi_note_to_note_octave_map[i] = [note_name,octave];
コード例 #2
0
ファイル: test_notes.py プロジェクト: MayankTi/python-mingus
 def test_int_to_note(self):
     known = {
             (0, '#'): 'C',
             (3, '#'): 'D#',
             (8, '#'): 'G#',
             (11, '#'): 'B',
             (0, 'b'): 'C',
             (3, 'b'): 'Eb',
             (8, 'b'): 'Ab',
             (11, 'b'): 'B'
             }
     for k in known.keys():
         self.assertEqual(known[k], notes.int_to_note(k[0], k[1]),
                 '%s with "%s" not corrisponding to %s, expecting %s' % (
                     k[0], k[1], notes.int_to_note(k[0], k[1]), known[k]))
コード例 #3
0
ファイル: magic.py プロジェクト: doino-gretchenliev/Mid-Magic
 def __call__(self, event, date = None ):
     
     event_types = (NOTE_ON, NOTE_OFF)
     if (event[0][0] & 0xF0) in event_types:
         if(event[0][1] < 60):
             self.scale = mapper.getMap(event[0][1]);
             self.midiout.send_message(event[0]);
         else:
             octave = event[0][1] / int(12);
             note = event[0][1] % 12;
             note_name = notes.int_to_note(note);
             print notes.note_to_int(self.scale[note_name]);
             event[0][1] = notes.note_to_int(self.scale[note_name]) + (12 * octave);
             self.midiout.send_message(event[0]);
             print notes.int_to_note(event[0][1] %12) + "(" + str(event[0][1]) +")" + " instead of " + notes.int_to_note(note) + "(" + str(note * octave) + ")";
コード例 #4
0
def main():
	file = open(FILENAME, 'r')
	obj = json.load(file)
	file.close()
	roots = obj['roots']
	operations = obj['chords']


	id = 0
	all_chords = []

	for function in operations:
		try: 
			method = getattr(chords, function)
			name = operations[function]
			for root in roots:
				notes_in_chord = method(root)
				fixed_notes = [notes.int_to_note(notes.note_to_int(elem)) for elem in notes_in_chord]
				chord_name = root + ' ' + name
				dict = {'notes' : fixed_notes, 'id' : id, 'name' : chord_name, 'type' : function, 'root' : root}
				all_chords.append(dict)
				id += 1
		except AttributeError:
			pass
	
	outFile = open(OUT_FILE, 'w')
	json.dump(all_chords, outFile)
	outFile.close()
コード例 #5
0
ファイル: voicing.py プロジェクト: 31415us/snooki-dj
def voice(old_voiced, nxt_chord):

    if old_voiced is None:
        return chords.from_shorthand(nxt_chord)

    old = [notes.note_to_int(n) for n in old_voiced]
    new = {notes.note_to_int(n) for n in chords.from_shorthand(nxt_chord)}

    res = []
    for note in old:
        if new:
            closest = min(new, key=lambda n: abs(note - n))
            res.append(closest)
            new.remove(closest)
        else:
            if len(old) == 4:
                res.append(res[0])

    for n in new:
        best_index = 0
        min_dist = 12
        for i in range(0, len(old)):
            dist = abs(old[i] - n)
            if dist < min_dist:
                min_dist = dist
                best_index = i

        res.insert(i, n)

    return [notes.int_to_note(n) for n in res]
コード例 #6
0
	def __init__(self, width, height):
		PygameVisualization.__init__(self, width, height)
		pygame.font.init()
		f = pygame.font.SysFont("monospace", width / 30)
		self.offsety = height % 24 / 2
		self.offsetx = width % 16 / 2 
		self.radius = height / 24 
		self.chanw = width / 32

		no = []
		for n in range(12):
			no.append(f.render(notes.int_to_note(n), 
				False, (169,169,169)))

		for x in range(17):
			if x % 2:
				pygame.draw.rect(self.raster, (230,230,230), 
					(x * self.chanw  * 2+ self.offsetx, 0, 
					self.chanw * 2, height))
		
		for x in range(17):
			pygame.draw.line(self.raster, (210,210,210),
				(x * self.chanw * 2 + self.offsetx ,0),
				(x * self.chanw * 2 + self.offsetx, height))
			for y in range(13):
				pygame.draw.line(self.raster, (200,200,200),
					(self.offsetx, y * self.radius * 2 + self.offsety), 
					(width - self.offsetx , y * self.radius * 2 + self.offsety))
				if y < 12:
					self.raster.blit(no[y], (x * self.chanw * 2 + self.chanw / 2 + self.offsetx, 
						y * self.radius * 2 + self.radius))
コード例 #7
0
ファイル: voicing.py プロジェクト: 31415us/snooki-dj
def voice(old_voiced, nxt_chord):

    if old_voiced is None:
        return chords.from_shorthand(nxt_chord)

    old = [notes.note_to_int(n) for n in old_voiced]
    new = {notes.note_to_int(n) for n in chords.from_shorthand(nxt_chord)}

    res = []
    for note in old:
        if new:
            closest = min(new, key=lambda n: abs(note - n))
            res.append(closest)
            new.remove(closest)
        else:
            if len(old) == 4:
                res.append(res[0])

    for n in new:
        best_index = 0
        min_dist = 12
        for i in range(0, len(old)):
            dist = abs(old[i] - n)
            if dist < min_dist:
                min_dist = dist
                best_index = i

        res.insert(i, n)


    return [notes.int_to_note(n) for n in res]
コード例 #8
0
def make_progression(base_chord, major):
    temp = notes.note_to_int(base_chord)
    base_chord = notes.int_to_note(temp, 'b')
    if (major):
        return progressions.to_chords(['I', 'V', 'VIm', 'IV'], base_chord)
    else:
        return progressions.to_chords(['Im', 'Vm', 'VI', 'IVm'], base_chord)
コード例 #9
0
ファイル: RandomSoloist.py プロジェクト: 0bill0/improviser
	def generate_note(self, state):
		if random() < state["wild"]:
			note = notes.int_to_note(randrange(0, 12))
			octave = randrange(2, 7)
			return [Note(note, octave)]
		else:
			return None
コード例 #10
0
 def test_int_to_note(self):
     known = {
         (0, '#'): 'C',
         (3, '#'): 'D#',
         (8, '#'): 'G#',
         (11, '#'): 'B',
         (0, 'b'): 'C',
         (3, 'b'): 'Eb',
         (8, 'b'): 'Ab',
         (11, 'b'): 'B'
     }
     for k in known.keys():
         self.assertEqual(
             known[k], notes.int_to_note(k[0], k[1]),
             '%s with "%s" not corrisponding to %s, expecting %s' %
             (k[0], k[1], notes.int_to_note(k[0], k[1]), known[k]))
コード例 #11
0
ファイル: Note.py プロジェクト: acekorg/downpoured_midi_audio
	def from_hertz(self, hertz, standard_pitch = 440):
		"""Sets the Note name and pitch, calculated from the `hertz` value. \
The `standard_pitch` argument can be used to set the pitch of A-4, from \
which the rest is calculated."""

		value = log(float(hertz) / standard_pitch, 2) * 12 + notes.note_to_int("A")
		self.name = notes.int_to_note(int(value) % 12)
		self.octave = int(value / 12) + 4
コード例 #12
0
 def test_int_to_note(self):
     known = {
         (0, "#"): "C",
         (3, "#"): "D#",
         (8, "#"): "G#",
         (11, "#"): "B",
         (0, "b"): "C",
         (3, "b"): "Eb",
         (8, "b"): "Ab",
         (11, "b"): "B",
     }
     for k in known:
         self.assertEqual(
             known[k],
             notes.int_to_note(k[0], k[1]),
             '%s with "%s" not corrisponding to %s, expecting %s' %
             (k[0], k[1], notes.int_to_note(k[0], k[1]), known[k]),
         )
コード例 #13
0
ファイル: ui.py プロジェクト: doino-gretchenliev/Mid-Magic
 def process_scale_change(self, scale):
     if len(scale) != 0 and len(self.current_note) != 0:
         note_name = notes.int_to_note(self.current_note[0]);
         scale_name = self.utils.getAvailableScales()[scale[0]];
         self.scale_to_map = self.mapper.getScaleToMap(note_name, scale_name);
         self.mapped_scale = self.cache.getScaleFromCache(note_name, scale_name);
         self.show_scale_to_buttons();
         self.auto_mode = False;
         self.showMessage(note_name + " - " + scale_name);
コード例 #14
0
ファイル: Note.py プロジェクト: ouimet51/mingus-python3
    def from_hertz(self, hertz, standard_pitch=440):
        """Sets the Note name and pitch, calculated from the `hertz` value. The \
`standard_pitch` argument can be used to set the pitch of A-4, from \
which the rest is calculated."""

        value = (log((float(hertz) * 1024) / standard_pitch, 2) + 1.0 / 24) * 12\
             + 9  # notes.note_to_int("A")
        self.name = notes.int_to_note(int(value) % 12)
        self.octave = int(value / 12) - 6
        return self
コード例 #15
0
ファイル: note.py プロジェクト: MayankTi/python-mingus
    def from_hertz(self, hertz, standard_pitch=440):
        """Set the Note name and pitch, calculated from the hertz value.

        The standard_pitch argument can be used to set the pitch of A-4,
        from which the rest is calculated.
        """
        value = ((log((float(hertz) * 1024) / standard_pitch, 2) +
            1.0 / 24) * 12 + 9)  # notes.note_to_int("A")
        self.name = notes.int_to_note(int(value) % 12)
        self.octave = int(value / 12) - 6
        return self
コード例 #16
0
 def to_dict(self):
     info = row2dict(self)
     info['match'] = []
     for k in self.keys:
         key, is_major = KEYS[k]
         key_result = {'key': notes.int_to_note(key), 'isMajor': is_major, 'forms': defaultdict(float)}
         for tf in TrackForm.get_forms(self):
             if tf.form.key == key:
                 key_result['forms'][tf.form.name] = tf.match
                 key_result['scale'] = tf.form.scale.name
         info['match'].append(key_result)
     return info
コード例 #17
0
ファイル: note.py プロジェクト: luciotorre/python-mingus
    def from_int(self, integer):
        """Set the Note corresponding to the integer.

        0 is a C on octave 0, 12 is a C on octave 1, etc.

        Example:
        >>> Note().from_int(12)
        'C-1'
        """
        self.name = notes.int_to_note(integer % 12)
        self.octave = integer // 12
        return self
コード例 #18
0
ファイル: note.py プロジェクト: MayankTi/python-mingus
    def from_int(self, integer):
        """Set the Note corresponding to the integer.

        0 is a C on octave 0, 12 is a C on octave 1, etc.

        Example:
        >>> Note().from_int(12)
        'C-1'
        """
        self.name = notes.int_to_note(integer % 12)
        self.octave = integer // 12
        return self
コード例 #19
0
ファイル: Note.py プロジェクト: acekorg/downpoured_midi_audio
	def from_int(self, integer):
		"""Sets the Note corresponding to the integer. 0 is a C on octave 0, \
12 is a C on octave 1, etc. 
{{{
>>> c = Note()
>>> c.from_int(12)
>>> c
'C-1'
}}}"""
		self.name = notes.int_to_note(integer % 12)
		self.octave = integer / 12
		return self
コード例 #20
0
    def from_hertz(self, hertz, standard_pitch: int = 440) -> 'Note':
        """Set the Note name and pitch, calculated from the hertz value.

        The standard_pitch argument can be used to set the pitch of A-4,
        from which the rest is calculated.
        """
        value = ((log(
            (float(hertz) * 1024) / standard_pitch, 2) + 1.0 / 24) * 12 + 9
                 )  # notes.note_to_int("A")
        self.name = notes.int_to_note(int(value) % 12)
        self.octave = int(value / 12) - 6
        return self
コード例 #21
0
ファイル: InstrumentDialog.py プロジェクト: 0bill0/improviser
	def setup(self):
		for x in Options.get_available_instruments():
			self.ui.algorithm.addItem(x)

		m = MidiInstrument()
		d = 1
		for x in m.names:
			self.ui.midi.addItem("%d. %s" % (d, x))
			d += 1

		self.connect(self.ui.algorithm, 
			QtCore.SIGNAL("activated(int)"),
			lambda x: self.load_instrument(self.ui.algorithm.currentText()))

		self.connect(self.ui.buttonBox,
			QtCore.SIGNAL("accepted()"),
			lambda: self.save_instrument())

		for x in range(116):
			self.ui.minnote.addItem("%s-%d" % (int_to_note(x % 12), x / 12 + 1))
			self.ui.maxnote.addItem("%s-%d" % (int_to_note(x % 12), x / 12 + 1))
コード例 #22
0
ファイル: Note.py プロジェクト: ouimet51/mingus-python3
    def from_int(self, integer):
        """Sets the Note corresponding to the integer. 0 is a C on octave 0, 12 is \
a C on octave 1, etc.
{{{
>>> c = Note()
>>> c.from_int(12)
>>> c
'C-1'
}}}"""

        self.name = notes.int_to_note(integer % 12)
        self.octave = integer // 12
        return self
コード例 #23
0
ファイル: utils.py プロジェクト: doino-gretchenliev/Mid-Magic
 def normalizeScale(self, scale):
     int_scale = {};
     note_scale = [];
     
     for note in scale:
         int_scale[notes.note_to_int(note)] = note;
     
     od = collections.OrderedDict(sorted(int_scale.items(), key=lambda t: t[0]));
     
     for key in od.iterkeys():
         note_scale.append(notes.int_to_note(key));
     
     return note_scale;
コード例 #24
0
ファイル: minevra.py プロジェクト: 9ae/3tonic
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
コード例 #25
0
def alternative_progression(key, major):
    if major:  #major
        first = notes.int_to_note((notes.note_to_int(key) + 9) % 12)
        second = notes.int_to_note((notes.note_to_int(key) + 7) % 12)
        third = notes.int_to_note((notes.note_to_int(key) + 5) % 12)
        return [[key, True], [first, False], [second, True], [third, True]]
    else:  #minor
        first = notes.int_to_note((notes.note_to_int(key) + 3) % 12)
        second = notes.int_to_note((notes.note_to_int(key) + 7) % 12)
        third = notes.int_to_note((notes.note_to_int(key) + 5) % 12)
        return [[key, False], [first, True], [second, False], [third, False]]
コード例 #26
0
 def test_valid_int_to_note(self):
     n = [
         'C',
         'C#',
         'D',
         'D#',
         'E',
         'F',
         'F#',
         'G',
         'G#',
         'A',
         'A#',
         'B',
         ]
     list(map(lambda x: self.assertEqual(n[x], notes.int_to_note(x),
         'Int to note mapping %d-%s failed.' % (x, n[x])), list(range(0, 12))))
コード例 #27
0
 def test_valid_int_to_note(self):
     n = [
         'C',
         'C#',
         'D',
         'D#',
         'E',
         'F',
         'F#',
         'G',
         'G#',
         'A',
         'A#',
         'B',
         ]
     map(lambda x: self.assertEqual(n[x], notes.int_to_note(x),
         'Int to note mapping %d-%s failed.' % (x, n[x])), range(0, 12))
コード例 #28
0
ファイル: visualizer.py プロジェクト: inniyah/python-mingus
    def __init__(self, outer_radius, inner_radius, ref_colors=None):
        self.notes = {
            int_to_note((i * 7) % 12, 'b'): None
            for i in range(0, 12)
        }  # Circle of fifths

        if ref_colors is None:
            ref_colors = {
                SectorRing.STATE_IDLE: [[255, 120, 12], [255, 8, 45]],
                SectorRing.STATE_PRESSED: [[0, 255, 255], [0, 128, 255]],
            }

        i = 0
        for note in self.notes:
            self.notes[note] = SectorRing.Sector(outer_radius, inner_radius,
                                                 math.pi / 6.4,
                                                 -2 * (i - 2) * math.pi / 12,
                                                 10, ref_colors)
            i += 1
コード例 #29
0
    def loop(self):
        buffer = self._stream.read(self._bufferSize)

        self.pitchTracker.Q.put(buffer)

        pitch = int(round(self.pitchTracker.pitch))

        if self.key != "":
            key = self.key[0]
            majorMinor = self.key[-5:]

            # Generate scale from key
            if majorMinor == "major":
                scale = scales.get_notes(key)
            else:
                scale = scales.get_notes(notes.reduce_accidentals(key + "###"))
                scale[4] = notes.reduce_accidentals(scale[4] + "#")

            note = notes.reduce_accidentals(notes.int_to_note(pitch % 12))
            if not note in scale:
                minDiff = 1000
                dPitch = 0
                for n in scale:
                    diff = abs(notes.note_to_int(n) - notes.note_to_int(note))
                    if diff < minDiff:
                        minDiff = diff
                        dPitch = notes.note_to_int(n) - notes.note_to_int(note)
                pitch += dPitch
            print(pitch)

            if pitch > 10:
                self._noAudio = 0
                self._maxLive.send_message("/pitch", pitch)
                self._maxLive.send_message("/key", notes.note_to_int(key))
            else:
                self._noAudio += 1
                print("*** No Audio! " + str(self._noAudio))
                if self._noAudio > 100:
                    self.done.set()
                    self.terminate()

        time.sleep(0.00001)
コード例 #30
0
def create_random_track(key, happy, bars):
    temp = notes.note_to_int(key)
    key = notes.int_to_note(temp, 'b')  #convert all accidentals to flats
    newTrack = Track()
    progressionChoice = alternative_progression(
        key, happy)  #get an array of the possible progressions
    prevProg = False
    for i in range(0, bars):
        curBar = Bar(key, (4, 4))
        if (prevProg):  #if it's not the first bar
            progIndex = prevProgInd + random.choice([1, -1])
            # make sure the current progression is next to the previous one
            if progIndex == -1:
                progIndex = 3
            elif progIndex == 4:
                progIndex = 0
        else:
            progIndex = random.choice(range(
                0, 4))  #the first progression is randmly chosen
        prevProg = True
        prevProgInd = progIndex
        useProgression = progressionChoice[progIndex]
        Progression = make_progression(useProgression[0],
                                       useProgression[1])  #get the progression
        prevChord = False
        while curBar.current_beat < 1:
            if (prevChord):  #if it's not the first chord
                chordIndex = prevInd + random.choice([1, -1])
                # to make sure the current chord is next to the previous one in the progression
                if chordIndex == -1:
                    chordIndex = 3
                elif chordIndex == 4:
                    chordIndex = 0
            else:
                chordIndex = random.choice(
                    range(0, 4)
                )  #the first chord is a random chord from the progression
            prevChord = True
            curBar.place_notes(Progression[chordIndex], 4)
            prevInd = chordIndex
        newTrack + curBar  #add bar to the track
    return newTrack
コード例 #31
0
ファイル: visualizer.py プロジェクト: inniyah/python-mingus
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        icon = pyglet.image.load(os.path.join(this_dir, 'icon.png'))
        self.set_icon(icon)
        self.set_minimum_size(300, 300)
        gl.glClearColor(0.2, 0.2, 0.21, 1)

        self.font = TrueTypeMonoFont("Liberation Mono", 64)

        self.inner_ring = SectorRing(
            0.8, 0.7, {
                SectorRing.STATE_IDLE: [[255, 120, 12], [255, 8, 45]],
                SectorRing.STATE_PRESSED: [[0, 255, 255], [0, 128, 255]],
            })

        self.outer_ring = SectorRing(
            0.85, 0.82, {
                SectorRing.STATE_IDLE: None,
                SectorRing.STATE_PRESSED: [[0, 255, 0], [0, 128, 0]],
            })

        self.midi_in = rtmidi.MidiIn()
        available_ports = self.midi_in.get_ports()
        if available_ports:
            midi_port_num = 1
            self.midi_in_port = self.midi_in.open_port(midi_port_num)
            print("Using MIDI Interface {}: '{}'".format(
                midi_port_num, available_ports[midi_port_num]))
        else:
            print("Creating virtual MIDI input.")
            self.midi_in_port = self.midi_in.open_virtual_port(
                "midi_driving_in")

        self.midi_in.set_callback(self.midi_received)

        self.key_map = {i: int_to_note(i, 'b') for i in range(0, 12)}
        self.press_counter = [0] * 12
        self.memory_counter = [0] * 12

        self.last_notes = FifoList()
コード例 #32
0
ファイル: Note.py プロジェクト: anzev/mingus
    def from_int(self, integer):
        """Sets the Note corresponding to the integer. 0 is a C on octave 0, \
12 is a C on octave 1, etc. 
{{{
>>> c = Note()
>>> c.from_int(12)
>>> c
'C-1'
}}}"""
        self.name = notes.int_to_note(integer % 12)
        self.octave = integer / 12
        return self

        def measure(self, other):
                """Returns the number of semitones between this Note and the other.
{{{
>>> Note("C").measure(Note("D"))
2
>>> Note("D").measure(Note("C"))
-2
}}}"""
                return int(other) - int(self)
コード例 #33
0
ファイル: graph.py プロジェクト: nmcasasr/Grafasol
 def get_scale(self):
     init_note = np.random.randint(0,12)
     scale = np.random.randint(1,12)
     note = notes.int_to_note(init_note)
     if(scale == 1):
         print("## Ionian Scale Selected!")
         return scales.Ionian(note)
     if(scale == 2):
         print("## Dorian Scale Selected!")
         return scales.Dorian(note)
     if(scale == 3):
         print("## Phrygian Scale Selected!")
         return scales.Phrygian(note)
     if(scale == 4):
         print("## Lydian Scale Selected!")
         return scales.Lydian(note)
     if(scale == 5):
         print("## Mixolydian Scale Selected!")
         return scales.Mixolydian(note)
     if(scale == 6):
         print("## Aeolian Scale Selected!")
         return scales.Aeolian(note)
     if(scale == 7):
         print("## Locrian Scale Selected!")
         return scales.Locrian(note)
     if(scale == 8):
         print("## NaturalMinor Scale Selected!")
         return scales.NaturalMinor(note)
     if(scale == 9):
         print("## HarmonicMinor Scale Selected!")
         return scales.HarmonicMinor(note)
     if(scale == 10):
         print("## MelodicMinor Scale Selected!")
         return scales.MelodicMinor(note)
     if(scale == 11):
         print("## WholeTone Scale Selected!")
         return scales.WholeTone(note)
コード例 #34
0
ファイル: utilities.py プロジェクト: samg7b5/sidewinder
    def assume_key(root, chord_type, mode):

        if mode == 'harmonic_minor':
            if chord_type in ['7b9']:
                # assume V (C7b9 implies F harmonic minor, i.e. 7b9 is phyrgian dominant (V mode of HM)) TODO: refactor?
                return notes.int_to_note(notes.note_to_int(root) - 7)

        if chord_type in ['M7', 'M9', 'M13', 'M6']:
            return root
        elif chord_type in ['m7', 'm9', 'm11', 'm13']:
            # assume II, e.g. Dm7 -> return C
            return notes.int_to_note(notes.note_to_int(root) - 2)
        elif chord_type in ['m7b9', 'm11b9', 'm13b9']:
            # assume III
            return notes.int_to_note(notes.note_to_int(root) - 4)
        elif '#11' in chord_type:
            # assume IV
            return notes.int_to_note(notes.note_to_int(root) - 5)
        elif chord_type in ['7', '9', '11', '13']:
            # assume V
            return notes.int_to_note(notes.note_to_int(root) - 7)
        elif chord_type in ['m7b13']:
            # assume VI
            return notes.int_to_note(notes.note_to_int(root) - 9)
        elif ('b5' in chord_type) or ('dim' in chord_type):
            # assume VII
            return notes.int_to_note(notes.note_to_int(root) - 11)
        elif chord_type in [
                '7b9'
        ]:  # TODO: refactor so that this is not an ad hoc exception (given 7b9 is covered below) but instea maybe automatically check all hminor modes etc
            pass
        else:
            print(
                f'\nWarning: utilities.assume_key() does not know how to handle chord_type {chord_type}'
            )
            pass
コード例 #35
0
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        bpm = 120
        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 len(b.bar) > 0:
                        current_length = b.bar[-1][1]
                        b.bar[-1][1] = duration
                        if current_length - duration != 0:
                            b.current_beat -= 1.0 / current_length
                            b.current_beat += 1.0 / duration
                    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 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 + b
            c.tracks.append(t)
        return (c, bpm)
コード例 #36
0
ファイル: utils.py プロジェクト: davidbegin/sandberg
def key_finder():
    return notes.int_to_note(random.randint(0, 11))
コード例 #37
0
ファイル: tonal.py プロジェクト: zee2theodd/machine_music
 def pick_base_note(self):
     """
     Randomly chooses a starting point for the scale when needed.
     :return:
     """
     return notes.int_to_note(random.randint(0, 11))
コード例 #38
0
 def __init__(self, tuning):
     if not 0 <= tuning < 12:
         raise ValueError(f"Tuning must be an integer in [0, 11].")
     self.notes = tuple(notes.int_to_note((tuning + fret) % 12) for fret in range(self.FRETS))
コード例 #39
0
import mingus.core.notes as notes
from mingus.midi import fluidsynth as fluidsynth
from math import sqrt

def fibonacci(n):
    return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))

first_hundred_fibs = [fibonacci(x) for x in range(100)]
fib_notes = [notes.int_to_note(x % 12) for x in first_hundred_fibs]

print first_hundred_fibs
print fib_notes

fluidsynth.init("RolandNicePiano.sf2")
for note in fib_notes:
    fluidsynth.play_Note(note)
コード例 #40
0
class Scale(Enum):
    IONIAN = 0
    DORIAN = 1
    PHRYGIAN = 2
    LYDIAN = 3
    MIXOLYDIAN = 4
    AEOLIAN = 5
    LOCRIAN = 6
    MINORPENTATONIC = 7
    MAJORPENTATONIC = 8
    MINORBLUES = 9
    MAJORBLUES = 10


NOTES_DICT = {notes.int_to_note(value, accidental): value for value in range(12) for accidental in ('#', 'b')}

KEYS = tuple((value, is_major) for is_major in (True, False) for value in range(12))
KEY_NAMES = tuple('C')

SCALES_DICT = {
    scales.Ionian: Scale.IONIAN,
    scales.Dorian: Scale.DORIAN,
    scales.Phrygian: Scale.PHRYGIAN,
    scales.Lydian: Scale.LYDIAN,
    scales.Mixolydian: Scale.MIXOLYDIAN,
    scales.Aeolian: Scale.AEOLIAN,
    scales.Locrian: Scale.LOCRIAN,
    scales.MinorPentatonic: Scale.MINORPENTATONIC,
    scales.MajorPentatonic: Scale.MAJORPENTATONIC,
    scales.MinorBlues: Scale.MINORBLUES,
コード例 #41
0
ファイル: Note.py プロジェクト: anzev/mingus
    def from_hertz(self, hertz, standard_pitch = 440):
        """Sets the Note name and pitch, calculated from the `hertz` value. \
The `standard_pitch` argument can be used to set the pitch of A-4, from \
which the rest is calculated."""

        value = log(float(hertz) / standard_pitch, 2) * 12 + notes.note_to_int("A")
        self.name = notes.int_to_note(int(value) % 12)
        self.octave = int(value / 12) + 4

        def to_shorthand(self):
                """Gives the traditional Helmhotz pitch notation.\
{{{
>>> Note("C-4").to_shorthand()
"c'"
>>> Note("C-3").to_shorthand()
'c'
>>> Note("C-2").to_shorthand()
'C'
>>> Note("C-1").to_shorthand()
'C,'
}}}"""
                if self.octave < 3:
                        res = self.name
                else:
                        res = str.lower(self.name)

                o = self.octave - 3
                while o < -1:
                        res += ","
                        o += 1
                while o > 0:
                        res += "'"
                        o -= 1
                return res

        def from_shorthand(self, shorthand):
                """Convert from traditional Helmhotz pitch notation.\
{{{
>>> Note().from_shorthand("C,,")
'C-0'
>>> Note().from_shorthand("C")
'C-2'
>>> Note().from_shorthand("c'")
'C-4'
}}}"""
                name = ""
                octave = 0
                for x in shorthand:
                        if x in ['a', 'b', 'c', 'd', 'e', 'f', 'g']:
                                name = str.upper(x)
                                octave = 3
                        elif x in ['A', 'B', 'C', 'D', 'E', 'F', 'G']:
                                name = x
                                octave = 2
                        elif x in ["#", "b"]:
                                name += x
                        elif x == ',':
                                octave -= 1
                        elif x == "'":
                                octave += 1
                return self.set_note(name, octave, {})
コード例 #42
0
# -*- coding: utf-8 -*-
#2018/8/26
#python2

import mingus.core.notes as notes

#检查音符合法性
notes.is_valid_note('C')  # True
#音符、值互转
notes.note_to_int('C')  # 0
notes.int_to_note(1)  # C#
#半音升降
notes.augment('C')  # C#
notes.diminish('C#')  # C
#大小调转化(无方法)
#notes.to_minor('C') # A
#notes.to_major('A') # C

#无模块
#import mingus.core.diatonic as diatonic
#十二音
#diatonic.basic_keys
#E调七音
#diatonic.get_notes('E')

import mingus.core.intervals as interval
#间隔半音数
interval.measure('C', 'D')  #2

import mingus.core.scales as scales
#爱奥尼音阶对象
コード例 #43
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)
コード例 #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:
			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
コード例 #45
0
ファイル: 1_3.py プロジェクト: sld2157/xylophone-dropzone
'''
Created on Jan 5, 2017

@author: stephenkoh
'''

import mingus.core.notes as notes

fibs = [1, 1]
for i in range(2, 1000):
    fibs.append(fibs[i - 2] + fibs[i - 1])
fib_notes = []
for n in fibs:
    fib_notes.append(notes.int_to_note(n % 12))
print(fibs)
print(len(fibs))
print(fib_notes)
print(len(fib_notes))
コード例 #46
0
ファイル: utils.py プロジェクト: doino-gretchenliev/Mid-Magic
 def normalizeNote(self, note):
     int_note = notes.note_to_int(note);
     return notes.int_to_note(int_note);
コード例 #47
0
 def pick_base_note(self):
     """Let me tell you what I am."""
     return notes.int_to_note(random.randint(0, 11))
コード例 #48
0
    key = dict_musickey[h]

    return (key)


#
#
#
#
#
if __name__ == "__main__":
    image = "Average-Color.png"

    avgcolor_img = cv2.imread(image)

    cica = more_average(avgcolor_img)
    print(cica)

    octave = pick_octave(cica)
    print("Octave: " + str(octave))

    major = pick_major(avgcolor_img)
    print("Major/Minor?: " + major)

    #pixel_key = pick_key(avgcolor_img) #Note: Overflow error. do key later

    note_list = []
    note_list.append(notes.augment("C"))
    note_list.append(notes.int_to_note(138 % 12))
    print(note_list)
コード例 #49
0
ファイル: MidiFileIn.py プロジェクト: valrus/mingus3
    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)
コード例 #50
0
ファイル: mingus_scratch.py プロジェクト: basilkar/notespace
import mingus.core.notes as notes
import mingus.core.keys as keys
import mingus.core.intervals as intervals

print(notes.is_valid_note('C#'))
print(notes.int_to_note(0))  # [0,..,11]

print(keys.get_notes("C"))

print(intervals.second("E", "C"))
print(intervals.determine("Gbb", "Ab"))
print(intervals.determine("Gbb", "Ab", True))
print(intervals.measure("C", "D"))
print(intervals.measure("D", "C"))
コード例 #51
0
    def handle(self, argv=None):
        """
        Main function.

        Parses command, load settings and dispatches accordingly.

        """
        help_message = "Please supply chord progression!. See --help for more options."
        parser = argparse.ArgumentParser(
            description=
            'chords2midi - Create MIDI files from written chord progressions.\n'
        )
        parser.add_argument('progression',
                            metavar='U',
                            type=str,
                            nargs='*',
                            help=help_message)
        parser.add_argument('-B',
                            '--bassline',
                            action='store_true',
                            default=False,
                            help='Throw an extra bassline on the pattern')
        parser.add_argument('-b',
                            '--bpm',
                            type=int,
                            default=80,
                            help='Set the BPM (default 80)')
        parser.add_argument('-t',
                            '--octave',
                            type=str,
                            default='4',
                            help='Set the octave(s) (ex: 3,4) (default 4)')
        parser.add_argument('-i',
                            '--input',
                            type=str,
                            default=None,
                            help='Read from an input file.')
        parser.add_argument('-k',
                            '--key',
                            type=str,
                            default='C',
                            help='Set the key (default C)')
        parser.add_argument('-n',
                            '--notes',
                            type=int,
                            default=99,
                            help='Notes in each chord (default all)')
        parser.add_argument('-d',
                            '--duration',
                            type=float,
                            default=1.0,
                            help='Set the chord duraction (default 1)')
        parser.add_argument(
            '-D',
            '--directory',
            action='store_true',
            default=False,
            help=
            'Output the contents to the directory of the input progression.')
        parser.add_argument(
            '-H',
            '--humanize',
            type=float,
            default=0.0,
            help=
            'Set the amount to "humanize" (strum) a chord, in ticks - try .11 (default 0.0)'
        )
        parser.add_argument(
            '-o',
            '--output',
            type=str,
            help=
            'Set the output file path. Default is the current key and progression in the current location.'
        )
        parser.add_argument(
            '-O',
            '--offset',
            type=float,
            default=0.0,
            help='Set the amount to offset each chord, in ticks. (default 0.0)'
        )
        parser.add_argument('-p',
                            '--pattern',
                            type=str,
                            default=None,
                            help='Set the pattern. Available patterns: ' +
                            (', '.join(patterns.keys())))
        parser.add_argument(
            '-r',
            '--reverse',
            action='store_true',
            default=False,
            help='Reverse a progression from C-D-E format into I-II-III format'
        )
        parser.add_argument('-v',
                            '--version',
                            action='store_true',
                            default=False,
                            help='Display the current version of chords2midi')

        args = parser.parse_args(argv)
        self.vargs = vars(args)

        if self.vargs['version']:
            version = pkg_resources.require("chords2midi")[0].version
            print(version)
            return

        # Support `c2m I III V and `c2m I,III,V` formats.
        if not self.vargs['input']:
            if len(self.vargs['progression']) < 1:
                print("You need to supply a progression! (ex I V vi IV)")
                return
            if len(self.vargs['progression']) < 2:
                progression = self.vargs['progression'][0].split(',')
            else:
                progression = self.vargs['progression']
        else:
            with open(self.vargs['input']) as fn:
                content = ''.join(fn.readlines()).strip()
                content = content.replace('\n', ' ').replace(',', '  ')
                progression = content.split(' ')
        og_progression = progression

        # If we're reversing, we don't need any of the MIDI stuff.
        if self.vargs['reverse']:
            result = ""
            key = self.vargs['key']
            for item in progression:
                comps = pychord.Chord(item).components()
                position = determine(comps, key, True)[0]
                if 'M' in position:
                    position = position.upper()
                    position = position.replace('M', '')
                if 'm' in position:
                    position = position.lower()
                    position = position.replace('m', '')
                if 'B' in position:
                    position = position + "b"
                    position = position.replace('B', '')

                result = result + position + " "
            print result
            return

        track = 0
        channel = 0
        ttime = 0
        duration = self.vargs['duration']  # In beats
        tempo = self.vargs['bpm']  # In BPM
        volume = 100  # 0-127, as per the MIDI standard
        bar = 0
        humanize_interval = self.vargs['humanize']
        directory = self.vargs['directory']
        num_notes = self.vargs['notes']
        offset = self.vargs['offset']
        key = self.vargs['key']
        octaves = self.vargs['octave'].split(',')
        root_lowest = self.vargs.get('root_lowest', False)
        bassline = self.vargs['bassline']
        pattern = self.vargs['pattern']

        # Could be interesting to do multiple parts at once.
        midi = MIDIFile(1)
        midi.addTempo(track, ttime, tempo)

        ##
        # Main generator
        ##
        has_number = False
        progression_chords = []

        # Apply patterns
        if pattern:
            if pattern not in patterns.keys():
                print("Invalid pattern! Must be one of: " +
                      (', '.join(patterns.keys())))
                return

            new_progression = []
            input_progression = progression[:]  # 2.7 copy
            pattern_mask = patterns[pattern]
            pattern_mask_index = 0
            current_chord = None

            while True:
                pattern_instruction = pattern_mask[pattern_mask_index]

                if pattern_instruction == "N":
                    if len(input_progression) == 0:
                        break
                    current_chord = input_progression.pop(0)
                    new_progression.append(current_chord)
                elif pattern_instruction == "S":
                    new_progression.append(current_chord)
                elif pattern_instruction == "X":
                    new_progression.append("X")

                if pattern_mask_index == len(pattern_mask) - 1:
                    pattern_mask_index = 0
                else:
                    pattern_mask_index = pattern_mask_index + 1
            progression = new_progression

        # We do this to allow blank spaces
        for chord in progression:

            # This is for # 'I', 'VI', etc
            progression_chord = to_chords(chord, key)
            if progression_chord != []:
                has_number = True

            # This is for 'C', 'Am', etc.
            if progression_chord == []:
                try:
                    progression_chord = [pychord.Chord(chord).components()]
                except Exception:
                    # This is an 'X' input
                    progression_chord = [None]

            chord_info = {}
            chord_info['notes'] = progression_chord[0]
            if has_number:
                chord_info['number'] = chord
            else:
                chord_info['name'] = chord

            if progression_chord[0]:
                chord_info['root'] = progression_chord[0][0]
            else:
                chord_info['root'] = None
            progression_chords.append(chord_info)

        # For each input..
        previous_pitches = []
        for chord_index, chord_info in enumerate(progression_chords):

            # Unpack object
            chord = chord_info['notes']
            # NO_OP
            if chord == None:
                bar = bar + 1
                continue
            root = chord_info['root']
            root_pitch = pychord.utils.note_to_val(
                notes.int_to_note(notes.note_to_int(root)))

            # Reset internals
            humanize_amount = humanize_interval
            pitches = []
            all_new_pitches = []

            # Turns out this algorithm was already written in the 1800s!
            # https://en.wikipedia.org/wiki/Voice_leading#Common-practice_conventions_and_pedagogy

            # a) When a chord contains one or more notes that will be reused in the chords immediately following, then these notes should remain, that is retained in the respective parts.
            # b) The parts which do not remain, follow the law of the shortest way (Gesetze des nachsten Weges), that is that each such part names the note of the following chord closest to itself if no forbidden succession XXX GOOD NAME FOR A BAND XXX arises from this.
            # c) If no note at all is present in a chord which can be reused in the chord immediately following, one must apply contrary motion according to the law of the shortest way, that is, if the root progresses upwards, the accompanying parts must move downwards, or inversely, if the root progresses downwards, the other parts move upwards and, in both cases, to the note of the following chord closest to them.
            root = None
            for i, note in enumerate(chord):

                # Sanitize notes
                sanitized_notes = notes.int_to_note(notes.note_to_int(note))
                pitch = pychord.utils.note_to_val(sanitized_notes)

                if i == 0:
                    root = pitch

                if root:
                    if root_lowest and pitch < root:  # or chord_index is 0:
                        pitch = pitch + 12  # Start with the root lowest

                all_new_pitches.append(pitch)

                # Reuse notes
                if pitch in previous_pitches:
                    pitches.append(pitch)

            no_melodic_fluency = False  # XXX: vargify
            if previous_pitches == [] or all_new_pitches == [] or pitches == [] or no_melodic_fluency:
                pitches = all_new_pitches
            else:
                # Detect the root direction
                root_upwards = None
                if pitches[0] >= all_new_pitches[0]:
                    root_upwards = True
                else:
                    root_upwards = False

                # Move the shortest distance
                if pitches != []:
                    new_remaining_pitches = list(all_new_pitches)
                    old_remaining_pitches = list(previous_pitches)
                    for i, new_pitch in enumerate(all_new_pitches):
                        # We're already there
                        if new_pitch in pitches:
                            new_remaining_pitches.remove(new_pitch)
                            old_remaining_pitches.remove(new_pitch)
                            continue

                    # Okay, so need to find the overall shortest distance from the remaining pitches - including their permutations!
                    while len(new_remaining_pitches) > 0:
                        nearest_distance = 9999
                        previous_index = None
                        new_index = None
                        pitch_to_add = None
                        for i, pitch in enumerate(new_remaining_pitches):
                            # XXX: DRY

                            # The Pitch
                            pitch_to_test = pitch
                            nearest = min(old_remaining_pitches,
                                          key=lambda x: abs(x - pitch_to_test))
                            old_nearest_index = old_remaining_pitches.index(
                                nearest)
                            if nearest < nearest_distance:
                                nearest_distance = nearest
                                previous_index = old_nearest_index
                                new_index = i
                                pitch_to_add = pitch_to_test

                            # +12
                            pitch_to_test = pitch + 12
                            nearest = min(old_remaining_pitches,
                                          key=lambda x: abs(x - pitch_to_test))
                            old_nearest_index = old_remaining_pitches.index(
                                nearest)
                            if nearest < nearest_distance:
                                nearest_distance = nearest
                                previous_index = old_nearest_index
                                new_index = i
                                pitch_to_add = pitch_to_test

                            # -12
                            pitch_to_test = pitch - 12
                            nearest = min(old_remaining_pitches,
                                          key=lambda x: abs(x - pitch_to_test))
                            old_nearest_index = old_remaining_pitches.index(
                                nearest)
                            if nearest < nearest_distance:
                                nearest_distance = nearest
                                previous_index = old_nearest_index
                                new_index = i
                                pitch_to_add = pitch_to_test

                        # Before we add it - just make sure that there isn't a better place for it.
                        pitches.append(pitch_to_add)
                        del old_remaining_pitches[previous_index]
                        del new_remaining_pitches[new_index]

                        # This is for the C E7 type scenario
                        if len(old_remaining_pitches) == 0:
                            for x, extra_pitch in enumerate(
                                    new_remaining_pitches):
                                pitches.append(extra_pitch)
                                del new_remaining_pitches[x]

                    # Final check - can the highest and lowest be safely folded inside?
                    max_pitch = max(pitches)
                    min_pitch = min(pitches)
                    index_max = pitches.index(max_pitch)
                    folded_max = max_pitch - 12
                    if (folded_max > min_pitch) and (folded_max
                                                     not in pitches):
                        pitches[index_max] = folded_max

                    max_pitch = max(pitches)
                    min_pitch = min(pitches)
                    index_min = pitches.index(min_pitch)

                    folded_min = min_pitch + 12
                    if (folded_min < max_pitch) and (folded_min
                                                     not in pitches):
                        pitches[index_min] = folded_min

                    # Make sure the average can't be improved
                    # XXX: DRY
                    if len(previous_pitches) != 0:
                        previous_average = sum(previous_pitches) / len(
                            previous_pitches)

                        # Max
                        max_pitch = max(pitches)
                        min_pitch = min(pitches)
                        index_max = pitches.index(max_pitch)
                        folded_max = max_pitch - 12

                        current_average = sum(pitches) / len(pitches)
                        hypothetical_pitches = list(pitches)
                        hypothetical_pitches[index_max] = folded_max
                        hypothetical_average = sum(hypothetical_pitches) / len(
                            hypothetical_pitches)
                        if abs(previous_average -
                               hypothetical_average) <= abs(previous_average -
                                                            current_average):
                            pitches[index_max] = folded_max
                        # Min
                        max_pitch = max(pitches)
                        min_pitch = min(pitches)
                        index_min = pitches.index(min_pitch)
                        folded_min = min_pitch + 12

                        current_average = sum(pitches) / len(pitches)
                        hypothetical_pitches = list(pitches)
                        hypothetical_pitches[index_min] = folded_min
                        hypothetical_average = sum(hypothetical_pitches) / len(
                            hypothetical_pitches)
                        if abs(previous_average -
                               hypothetical_average) <= abs(previous_average -
                                                            current_average):
                            pitches[index_min] = folded_min

                # Apply contrary motion
                else:
                    print("Applying contrary motion!")
                    for i, new_pitch in enumerate(all_new_pitches):
                        if i == 0:
                            pitches.append(new_pitch)
                            continue

                        # Root upwards, the rest move down.
                        if root_upwards:
                            if new_pitch < previous_pitches[i]:
                                pitches.append(new_pitch)
                            else:
                                pitches.append(new_pitch - 12)
                        else:
                            if new_pitch > previous_pitches[i]:
                                pitches.append(new_pitch)
                            else:
                                pitches.append(new_pitch + 12)

            # Bassline
            if bassline:
                pitches.append(root_pitch - 24)

            # Melody

            # Octave is a simple MIDI offset counter
            for octave in octaves:
                for note in pitches:
                    pitch = int(note) + (int(octave.strip()) * 12)

                    # Don't humanize bassline note
                    if bassline and (pitches.index(note) == len(pitches) - 1):
                        midi_time = offset + bar
                    else:
                        midi_time = offset + bar + humanize_amount

                    # Write the note
                    midi.addNote(track=track,
                                 channel=channel,
                                 pitch=pitch,
                                 time=midi_time,
                                 duration=duration,
                                 volume=volume)

                humanize_amount = humanize_amount + humanize_interval
                if i + 1 >= num_notes:
                    break
            bar = bar + 1
            previous_pitches = pitches

        ##
        # Output
        ##

        if self.vargs['output']:
            filename = self.vargs['output']
        elif self.vargs['input']:
            filename = self.vargs['input'].replace('.txt', '.mid')
        else:
            if has_number:
                key_prefix = key + '-'
            else:
                key_prefix = ''

            filename = key_prefix + '-'.join(og_progression) + '-' + str(tempo)
            if bassline:
                filename = filename + "-bassline"
            if pattern:
                filename = filename + "-" + pattern
            if os.path.exists(filename):
                filename = key_prefix + '-'.join(og_progression) + '-' + str(
                    tempo) + '-' + str(int(time.time()))
            filename = filename + '.mid'

            if directory:
                directory_to_create = '-'.join(og_progression)
                try:
                    os.makedirs(directory_to_create)
                except OSError as exc:  # Python >2.5
                    if exc.errno == errno.EEXIST and os.path.isdir(
                            directory_to_create):
                        pass
                    else:
                        raise
                filename = directory_to_create + '/' + filename

        with open(filename, "wb") as output_file:
            midi.writeFile(output_file)