Beispiel #1
0
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]
Beispiel #2
0
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]
def measure(note1, note2):
    """Return an integer in the range of 0-11, determining the half note steps
    between note1 and note2.

    Examples:
    >>> measure('C', 'D')
    2
    >>> measure('D', 'C')
    10
    """
    res = notes.note_to_int(note2) - notes.note_to_int(note1)
    if res < 0:
        return 12 - res * -1
    else:
        return res
Beispiel #4
0
def measure(note1, note2):
    """Return an integer in the range of 0-11, determining the half note steps
    between note1 and note2.

    Examples:
    >>> measure('C', 'D')
    2
    >>> measure('D', 'C')
    10
    """
    res = notes.note_to_int(note2) - notes.note_to_int(note1)
    if res < 0:
        return 12 - res * -1
    else:
        return res
Beispiel #5
0
 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) + ")";
Beispiel #6
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()
Beispiel #7
0
    def find_note_names(
        self,
        notelist,
        string=0,
        maxfret=24,
        ):
        """Returns a list [(fret, notename)] in ascending order.
Notelist should be a list of Notes, note-strings or a NoteContainer.
{{{
>>> t = tunings.StringTuning(\"test\", \"test\", ['A-3', 'A-4'])
>>> t.find_note_names([\"A\", \"C\", \"E\"], 0, 12)
[(0, 'E'), (5, 'A'), (8, 'C'), (12, 'E')]
}}}"""

        n = notelist
        if notelist != [] and type(notelist[0]) == str:
            n = NoteContainer(notelist)
        result = []
        names = [x.name for x in n]
        int_notes = [notes.note_to_int(x) for x in names]

                # Base of the string

        s = int(self.tuning[string]) % 12
        for x in range(0, maxfret + 1):
            if (s + x) % 12 in int_notes:
                result.append((x, names[int_notes.index((s + x) % 12)]))
        return result
Beispiel #8
0
    def addquickchordinselection(self, text, midi):
        if text:
            colonindex = text.find(";")
            if colonindex < 0:
                chordtext = text
                arptext = ""
            else:
                chordtext = text[0:colonindex]
                arptext = text[colonindex + 1:]

            try:
                chordlist = CHORDS.from_shorthand(chordtext)
            except:
                self.setalert("onbekende chord.")
                chordlist = []

            if chordlist:
                for i in range(len(chordlist)):
                    chordlist[i] = NOTES.note_to_int(chordlist[i])
                chordlist = list(set(chordlist))
                chordlist.sort()

                tickmin, tickmax, midimin, midimax = self.getselectionregion()
                self.addchordinregion(chordlist, [tickmin, tickmax],
                                      [midimin, midimax], arptext)
                self.setcurrentticksandload(self.currentabsoluteticks)
                #self.anchor = 0
        self.setstate(state=self.NAVIGATIONstate)
        return {}
    def find_note_names(
        self,
        notelist,
        string=0,
        maxfret=24,
        ):
        """Returns a list [(fret, notename)] in ascending order.
Notelist should be a list of Notes, note-strings or a NoteContainer.
{{{
>>> t = tunings.StringTuning(\"test\", \"test\", ['A-3', 'A-4'])
>>> t.find_note_names([\"A\", \"C\", \"E\"], 0, 12)
[(0, 'E'), (5, 'A'), (8, 'C'), (12, 'E')]
}}}"""

        n = notelist
        if notelist != [] and type(notelist[0]) == str:
            n = NoteContainer(notelist)
        result = []
        names = [x.name for x in n]
        int_notes = [notes.note_to_int(x) for x in names]

                # Base of the string

        s = int(self.tuning[string]) % 12
        for x in xrange(0, maxfret + 1):
            if (s + x) % 12 in int_notes:
                result.append((x, names[int_notes.index((s + x) % 12)]))
        return result
Beispiel #10
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)
Beispiel #11
0
def get_interval(note, interval, key='C'):
    """Return the note an interval (in half notes) away from the given note.

    This will produce mostly theoretical sound results, but you should use
    the minor and major functions to work around the corner cases.
    """
    intervals = list(
        map(lambda x: (notes.note_to_int(key) + x) % 12, [
            0,
            2,
            4,
            5,
            7,
            9,
            11,
        ]))
    key_notes = keys.get_notes(key)
    for x in key_notes:
        if x[0] == note[0]:
            result = (intervals[key_notes.index(x)] + interval) % 12
    if result in intervals:
        return key_notes[intervals.index(result)] + note[1:]
    else:
        return notes.diminish(key_notes[intervals.index((result + 1) % 12)] +
                              note[1:])
Beispiel #12
0
	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
Beispiel #13
0
 def calculate_caged_form(cls, key, scale, form, form_start=0, transpose=False):
     """
     Calculates the notes belonging to this shape. This is done as follows:
     Find the notes on the 6th string belonging to the scale, and pick the first one that is on a fret >= form_start.
     Then progressively build the scale, go to the next string if the distance between the start and the note is
     greater than 3 frets (the pinkie would have to stretch and it's easier to get that note going down a string).
     If by the end not all the roots are included in the form, call the function again and start on an higher fret.
     """
     strings = (None,) + tuple(String(note) for note in STANDARD_TUNING)
     # Indexes of string for each root form
     root_forms = {
         'C': (2, 5),
         'A': (5, 3),
         'G': (3, 1, 6),
         'E': (1, 6, 4),
         'D': (4, 2),
     }
     l_string = root_forms[form][0]  # string that has the leftmost root
     r_strings = root_forms[form][1:]  # other strings
     notes_list = []
     roots = [next((l_string, fret) for fret in strings[l_string][key] if fret >= form_start)]
     roots.extend(next((string, fret) for fret in strings[string][key] if fret >= roots[0][1])
                  for string in r_strings)
     scale_notes = scale(key).ascending()
     candidates = strings[6].get_notes(scale_notes)
     # picks the first note that is inside the form
     notes_list.append(next((6, fret) for fret in candidates if fret >= form_start))
     start = notes_list[0][1]
     for i in range(6, 0, -1):
         string = strings[i]
         if i == 1:
             # Removes the note added on the high E and just copy-pastes the low E
             notes_list.pop()
             # Copies the remaining part of the low E in the high E
             for note, fret in ((s, fret) for s, fret in notes_list.copy() if s == 6):
                 notes_list.append((1, fret))
             break
         for fret in string.get_notes(scale_notes):
             if fret <= start:
                 continue
             # picks the note on the higher string that is closer to the current position of the index finger
             higher_string_fret = min(strings[i - 1].get_notes([string.notes[fret]]),
                                      key=lambda x: abs(start - x))
             # No note is present in a feasible position on the higher string.
             if higher_string_fret > fret:
                 return cls.calculate_caged_form(key, scale, form, form_start=form_start + 1, transpose=transpose)
             # A note is too far if the pinkie has to go more than 3 frets away from the index finger
             if fret - start > 3:
                 notes_list.append((i - 1, higher_string_fret))
                 start = higher_string_fret
                 break
             else:
                 notes_list.append((i, fret))
     if not set(roots).issubset(set(notes_list)):
         return cls.calculate_caged_form(key, scale, form, form_start=form_start + 1, transpose=transpose)
     key = notes.note_to_int(key)
     scale = getattr(Scale, scale.__name__.upper())
     return cls(notes_list, key, scale, form, transpose=transpose)
Beispiel #14
0
 def on_beastie_attack(self, beastie, is_attacking):
     note_highlight = beastie.attack.hl
     if is_attacking:
         if note_highlight:
             key_index = note_to_int(note_highlight.name)
             self.kb.annotate(key_index, "rgb", [1., 0.5, 0.5])
     else:
         self.kb.clear_annotations()
         self.next_on_deck()
Beispiel #15
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)
Beispiel #16
0
 def create_midi_note_range(self, scale, base_note):
     """Let me tell you what I am."""
     beginning_scale = ts.select_scale(scale, base_note).ascending()
     begin_midi = [notes.note_to_int(note) for note in beginning_scale]
     midi_range = [note for note in begin_midi]
     for item in begin_midi:
         for x in range(16):
             new = self.add_octave(item, x)
             if new <= 120:
                 midi_range.append(new)
     return midi_range
Beispiel #17
0
    def __int__(self):
        """Returns the current octave multiplied by twelve and adds \
notes.note_to_int to it. This means a C-0 returns 0, C-1 \
returns 12, etc. This method allows you to use int() on Notes."""
        res = self.octave * 12 + notes.note_to_int(self.name[0])
        for n in self.name[1:]:
            if n == '#':
                res += 1
            elif n== 'b':
                res -= 1
        return res
Beispiel #18
0
def assign_octaves(chord, octave):

    ch = []
    last_int = None
    for n in chord:
        note_int = notes.note_to_int(n)
        if last_int and note_int < last_int:
            octave += 1
        note_string = '%s-%d'%(n, octave)
        ch.append(note_string)
        last_int = note_int
    return ch
Beispiel #19
0
    def __int__(self):
        """Returns the current octave multiplied by twelve and adds \
notes.note_to_int to it. This means a C-0 returns 0, C-1 returns 12, \
etc. This method allows you to use int() on Notes."""

        res = self.octave * 12 + notes.note_to_int(self.name[0])
        for n in self.name[1:]:
            if n == '#':
                res += 1
            elif n == 'b':
                res -= 1
        return res
Beispiel #20
0
def assign_octaves(chord, octave):

    ch = []
    last_int = None
    for n in chord:
        note_int = notes.note_to_int(n)
        if last_int and note_int < last_int:
            octave += 1
        note_string = '%s-%d' % (n, octave)
        ch.append(note_string)
        last_int = note_int
    return ch
Beispiel #21
0
 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;
Beispiel #22
0
def note_int(note): # duplicate of mingus.containers.note.Note.__int__(self)
        """Return the current octave multiplied by twelve and add
        notes.note_to_int to it.

        This means a C-0 returns 0, C-1 returns 12, etc. This method allows
        you to use int() on Notes.
        """
        res = note.octave * 12 + notes.note_to_int(note.name[0])
        for n in note.name[1:]:
            if n == '#':
                res += 1
            elif n == 'b':
                res -= 1
        return int(res)
Beispiel #23
0
    def __int__(self):
        """Return the current octave multiplied by twelve and add
        notes.note_to_int to it. This means a C-0 returns 0, C-1 returns 12,
        etc. This method allows you to use int() on Notes.
        """

        # We can assume that the note works correctly because it was initialized
        # with a check
        res = self.octave * 12 + notes.note_to_int(self.name[0])
        for char in self.name[1:]:
            if char == '#':
                res += 1
            elif char == 'b':
                res -= 1
        return res
Beispiel #24
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]]
Beispiel #25
0
 def __getSoundArr(self, startOc=4):
     tmp = []
     scl = self.__scaleArray()
     if (self.scaleName.split(' ')[0].lower() == "custom"):
         oc = self.__buildCustomScale(
             self.scaleName.split(' ')[1])['octave']
     else:
         oc = startOc
     lastNoteInt = 0  # Prevent first note from incrementing octave
     for note in scl:
         # When int value of note wraps to 0, octave should increment
         noteInt = notes.note_to_int(note)
         if noteInt < lastNoteInt:
             oc += 1
         lastNoteInt = noteInt
         tmp.append(NoteContainer(Note(note, oc)))
     return tmp
Beispiel #26
0
    def create_midi_note_range(self, scale, base_note):
        """
        Builds a note range within a given scale and starting note.

        :param scale:
        :param base_note:
        :return:
        """
        beginning_scale = TS.select_scale(scale, base_note).ascending()
        begin_midi = [notes.note_to_int(note) for note in beginning_scale]
        midi_range = [note for note in begin_midi]
        for item in begin_midi:
            for x in range(16):
                new = self.add_octave(item, x)
                if new <= 120:
                    midi_range.append(new)
        return midi_range
Beispiel #27
0
def parse_track(song, track, tempo):
    """
    Iterates the track beat by beat and checks for matches
    """
    logger.info(f"Parsing track {track.name}")
    tuning = [notes.note_to_int(str(string)[0]) for string in track.strings]
    measure_match = defaultdict(
        list)  # measure: list of indexes the measure occupies in the track
    keyfinder = KeyFinder()
    note_durations = [0] * 12
    segment_duration = 0
    for i, m in enumerate(track.measures):
        beats = []
        for beat in m.voices[0].beats:  # fixme handle multiple voices
            beat = Beat.get_or_create(beat)
            beats.append(beat)
            # k-s analysis
            beat_duration = Fraction(1 / beat.duration)
            for note in beat.notes:
                note_value = (tuning[note.string - 1] + note.fret) % 12
                note_durations[note_value] += beat_duration
            # Does not increment segment duration if we had just pauses since now
            if any(duration for duration in note_durations):
                segment_duration += beat_duration
        measure = Measure.get_or_create(beats)
        measure_match[measure].append(i)
        # k-s analysis
        # tempo is expressed in quarters per minute. When we reached a segment long enough, start key analysis
        # if segment_duration * 4 * 60 / tempo >= KS_SECONDS or m is track.measures[-1]:
        # Current implementation: make analysis at the end of each measure.
        keyfinder.insert_durations(note_durations)
        segment_duration = 0
        note_durations = [0] * 12
    # Updates database objects
    track = Track(song_id=song.id, tuning=tuning, keys=[])
    for measure, indexes in measure_match.items():
        tm = TrackMeasure(track=track,
                          measure=measure,
                          match=len(track.measures),
                          indexes=indexes)
        db.session.add(tm)
    # Calculates matches of track against form given the keys
    results = keyfinder.get_results()
    for k in set(results):
        track.add_key(k)
    return track
Beispiel #28
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
Beispiel #29
0
    def find_note_names(self, notelist, string=0, maxfret=24):
        """Return a list [(fret, notename)] in ascending order.

        Notelist should be a list of Notes, note-strings or a NoteContainer.

        Example:
        >>> t = StringTuning('test', 'test', ['A-3', 'A-4'])
        >>> t.find_note_names(['A', 'C', 'E'], 0, 12)
        [(0, 'E'), (5, 'A'), (8, 'C'), (12, 'E')]
        """
        n = notelist
        if notelist != [] and isinstance(notelist[0], six.string_types):
            n = NoteContainer(notelist)
        result = []
        names = [x.name for x in n]
        int_notes = [notes.note_to_int(x) for x in names]

        # Base of the string
        s = int(self.tuning[string]) % 12
        for x in range(0, maxfret + 1):
            if (s + x) % 12 in int_notes:
                result.append((x, names[int_notes.index((s + x) % 12)]))
        return result
Beispiel #30
0
def get_interval(note, interval, key='C'):
    """Return the note an interval (in half notes) away from the given note.

    This will produce mostly theoretical sound results, but you should use
    the minor and major functions to work around the corner cases.
    """
    intervals = list(map(lambda x: (notes.note_to_int(key) + x) % 12, [
        0,
        2,
        4,
        5,
        7,
        9,
        11,
        ]))
    key_notes = keys.get_notes(key)
    for x in key_notes:
        if x[0] == note[0]:
            result = (intervals[key_notes.index(x)] + interval) % 12
    if result in intervals:
        return key_notes[intervals.index(result)] + note[1:]
    else:
        return notes.diminish(key_notes[intervals.index((result + 1) % 12)]
                               + note[1:])
Beispiel #31
0
    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
Beispiel #32
0
 def normalizeNote(self, note):
     int_note = notes.note_to_int(note);
     return notes.int_to_note(int_note);
Beispiel #33
0
  if(len(b_waves) > 100):
    b_waves.pop(0)

def is_peak(freqs):
  minf = min(freqs)
  maxf = max(freqs)


p = progressions.to_chords(chords[mood])
print progressions.to_chords(p, "D")


for k, chord in enumerate(p):
	temp = []
	for j, note in enumerate(chord):
		temp.append(60 + notes.note_to_int(note))
	print temp
	p[k] = temp

i=0
j=0
curchord = 0
#n iterations of while loop
chord_length = 4
index = 0
offset = 0
speed = 1
sleeptime = 0.5
try:
  while(1):
    print i
Beispiel #34
0
def midify(chord, key='A', octave=-2):
    tonic = (60 + (12 * octave)) + notes.note_to_int(key)
    return [midiToHz(tonic + notes.note_to_int(x)) for x in chord]
Beispiel #35
0
'''
Created on Jan 6, 2017

@author: stephenkoh
'''

import mingus.core.keys as keys
import mingus.core.notes as notes
#import mingus.core.intervals as intervals

for i in range(len(keys.keys)):
    key = keys.keys[i][0]
    note_int = notes.note_to_int(key)
    note1 = keys.int_to_note(note_int, key)
    note2 = notes.int_to_note(note_int)
    #if (intervals.measure(note1, note2) == 0):
    if (note1 != note2):
        print('Using notes.int_to_note: %s\n\
Using keys.int_to_note: %s\n\
Number: %d\nKey: %s\n' % (note1, note2, note_int, key))
Beispiel #36
0
 def test_to_int(self):
     self.assertEqual(0, to.note_to_int("C"))
     self.assertEqual(11, notes.note_to_int("Cb"))
     with self.assertRaises(TypeError):
         to.note_to_int(0)
Beispiel #37
0
 def test_pick_base_note(self):
     self.assertIn(notes.note_to_int(to.pick_base_note()), range(0, 13))
def targetYN():
    print(
        "GOAL: Choose a target pitch. Listen to a random melody: is the target pitch in there? If yes, play it again, and type in the index of the pitch (i.e. what number does it fall in the sequence: 1, 2, 3 ...).\n"
    )
    pcSought_in = input("Which pc are you listening for? (0-11) > ")

    try:
        pcSought = int(pcSought_in)
    except:
        print("Error. Please type an integer 0-11.")
        return

    if pcSought < 0 or pcSought > 11:
        print("Error. Please type an integer 0-11.")

    numnotes_in = input("Please choose a melody length. (1-16) > ")

    try:
        numnotes = int(numnotes_in)
    except:
        print("Error. Please type an integer 1-16.")
        return

    if numnotes < 1 or numnotes > 16:
        print("Error. Please type an integer 1-16.")
        return

    loopTarget = True

    while (loopTarget):
        randInstrument(1)

        randNotes = []
        randBar = Bar()
        randBar.set_meter((numnotes, 4))
        pitch_list = []
        for i in range(0, numnotes):
            randPitch = Note(12 * randint(3, 6) + randint(0, 12))
            randNotes.append(randPitch)
            pitch_list.append(notes.note_to_int(randPitch.name))
            randBar.place_notes(randPitch, 4)

        fluidsynth.play_Bar(randBar)

        note_present = False
        if (pcSought in pitch_list):
            note_present = True

        present_in = input("Was the desired note present? (Y/N) > ")

        player_thinks = False

        if present_in.lower() == "y":
            player_thinks = True

        if player_thinks == note_present:
            print("Correct! The note", end="")
            if note_present:
                print(" was present.\n")
            else:
                print(" was not present.\n")
        else:
            print("Incorrect. The note\n", end="")
            if note_present:
                print(" was present.\n")
            else:
                print(" was not present.\n")

        if note_present:
            print(
                "Press ENTER to replay, then type where in the sequence the note appears."
            )
            fluidsynth.play_Bar(randBar)
            locations_in = input(
                "Enter the indices of the note, starting with 1, and separated by spaces. > "
            )
            #string processing: make an array from the input. Make an array of the pitch locations. Compare. Are they correct? Output the array.

        print(randNotes)
        loopTarget = playAfterAnswer(randBar)
Beispiel #39
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)
Beispiel #40
0
def note_to_int(note, key):
    if (Notes.note_to_int(note) >= Notes.note_to_int(key)):
        return Notes.note_to_int(note) - Notes.note_to_int(key)
    else:
        return 12 - (Notes.note_to_int(key) - Notes.note_to_int(note))
Beispiel #41
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
#爱奥尼音阶对象
 def play_Note(self, note, channel = 0, velocity = 100):
     if MidiSequencer.play_Note(self, note, channel, velocity):
        print self.i, "(",note,'--',fixed[notes.note_to_int(note.name)],
        sys.stdout.flush()
        self.i += 1
        return True
Beispiel #43
0
    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, {})
Beispiel #44
0
'''
Created on Jan 5, 2017

@author: stephenkoh
'''

import mingus.core.notes as notes

note = str(input("Please enter a note: "))
if (notes.is_valid_note(note)):
    for i in range(4):
        note = notes.augment(note)
note_int = notes.note_to_int(note)
note = notes.int_to_note(note_int)
print(note)