def check_melody_intervals(track): # The melody we test is the track melody without pauses. It will work if the melody has multiple pitches # in the same noteContainer, but it uses the first note in each container. A way to make it smarter would # be to use the highest pitch, but I don't think that's necessary for now melody = [note[2][0] for note in track.get_notes() if note[2]] good_intervals = [0, 1, 2, 3, 4, 5, 7, 12] if len(melody) <= 1: return 0.0 # count number of good intervals nmb = 0 for i in range(len(melody) - 1): interval = Note(melody[i]).measure(Note(melody[i + 1])) if abs(interval) in good_intervals: nmb += 1 # one point if good interval elif interval in [8, 9] and i + 2 < len(melody): # if the interval was a sixth up, count as good only if it is followed by downward motion # (doesn't matter here what kind of downward motion - if it's 'good', it will get a point # in the next iteration of the loop) next_interval = Note(melody[i + 1]).measure(Note(melody[i + 2])) if next_interval < 0: nmb += 1 # return fraction of good intervals in the melody return nmb / (len(melody) - 1)
def play_midi(chords): from EasyMIDI import EasyMIDI,Track,Note,Chord,RomanChord from random import choice easyMIDI = EasyMIDI() track1 = Track("acoustic grand piano") # oops # print(chords) for chord_dict in chords: root = Note(chord_dict[0]['note'], chord_dict[0]['octave']-2) # MAKE THE TRIAD I = Note(chord_dict[0]['note'], chord_dict[0]['octave'], duration = 0.2) III = Note(chord_dict[1]['note'], chord_dict[1]['octave'], duration = 0.5) IV = Note(chord_dict[2]['note'], chord_dict[2]['octave'], duration = 0.01) chord = Chord([root, I,III,IV]) # a chord of notes C, E and G track1.addNotes(chord) # roman numeral chord, first inversion (defaults to key of C) # track1.addNotes(RomanChord('I*', octave = 5, duration = 1)) easyMIDI.addTrack(track1) easyMIDI.writeMIDI("output.mid") os.system("timidity output.mid -Ow -o out.wav") os.system("open out.wav")
class BassInstrument(Instrument): name = '' range = (Note('C', 0), Note('C', 10)) clef = 'Bass' def __init__(self, name): self.name = name Instrument.__init__(self)
def scale2ints(minguscale, key='C', span=2, octave=3): scale = minguscale(key, span) notas = [] for o in range(octave, octave + span): for n in range(7): notas.append(int(Note(scale.ascending()[n], o))) notas.append(int(Note(scale.tonic, octave + span))) return notas
def __init__(self, starting_note='C-3'): fluidsynth.init(path_to_instrument, audio_driver) self.starting_note = Note(starting_note) self.relative_major_scale = np.array([0, 2, 4, 5, 7, 9, 11]) self.scale = self.relative_major_scale + int(self.starting_note) self.note = Note(self.starting_note) self.bar = Bar() fluidsynth.play_Note(self.note)
def second_voice_ending(second_track, key): first = key fourth = intervals.fourth(key, key) fifth = intervals.fifth(key, key) second_track.add_notes(Note(first, 3), 2) second_track.add_notes(Note(fourth, 3), 2) second_track.add_notes(Note(fifth, 3), 2) second_track.add_notes(Note(fifth, 3), 1)
def changeOctave(notes, value): result = [] if isinstance(notes, list): for note in notes: n = Note(note) n.change_octave(value) result.append(n) else: n = Note(notes) n.change_octave(value) result = n return result
def eval_single(usr_ans, question, root_note): correct_ = False if usr_ans == str(numerals.index(question) + 1): correct_ = True else: try: usr_note_val = int(Note(usr_ans[0].upper() + usr_ans[1:])) % 12 correct_note_val = int(Note(root_note)) % 12 if usr_note_val == correct_note_val: correct_ = True except: pass return correct_
def play_notes(fs): key = random_key() print key # fs.play_Note(Note('C-5')) # fs.play_NoteContainer(NoteContainer(chords.major_triad(key))) # fs.play_Bar(get_bar_from_triad(chords.major_triad(key))) fs.play_Note(Note('Cb-4')) ## this is B-3, not B-4 fs.play_Note(Note('B-3')) # print(_make_ascending(chords.major_triad(key))) a = raw_input('hello?')
def eval_single_chord(usr_ans, correct_numeral, root_note): correct_ = False if usr_ans == str(st.NUMERALS.index(correct_numeral) + 1): correct_ = True else: try: usr_note_val = int(Note(usr_ans[0].upper() + usr_ans[1:])) % 12 correct_note_val = int(Note(root_note)) % 12 if usr_note_val == correct_note_val: correct_ = True except: pass return correct_
def parse2note(x): if isinstance(x, int): return Note().from_int(x) # if integer elif isinstance(x, str): try: return Note().from_int(str(x)) # if integer string except: return Note(x) # if string note name elif isinstance(x, Note): return x # if already Note else: raise Exception("Could not parse input {} of type {} to string." "".format(x, type(x)))
def cbNotasChanged(self, idx): n1 = str(self.cbNota1.itemText(self.cbNota1.currentIndex())) n2 = str(self.cbNota2.itemText(self.cbNota2.currentIndex())) n3 = str(self.cbNota3.itemText(self.cbNota3.currentIndex())) e1 = self.cbEscala1.currentIndex() e2 = self.cbEscala2.currentIndex() e3 = self.cbEscala3.currentIndex() print "Notas: %s%d - %s%d - %s%d" % (n1, e1, n2, e2, n3, e3) self.soundCommand1 = Note(n1, e1) self.soundCommand2 = Note(n2, e2) self.soundCommand3 = Note(n3, e3)
def shell_voice(progression, durations, prog_type='shorthand', roots=False, extensions=False): ''' shell voice: play just the 3rd and 7th (as the most harmonic) (cf http://www.thejazzpianosite.com/jazz-piano-lessons/jazz-chords/shell-chords/) potentially also add extensions. extensions flag is to by default filter out any extensions above 7th, otherwise cf http://www.jamieholroydguitar.com/how-to-play-shell-voicings/ ''' chords_ = progression_to_chords(progression, prog_type) # save them if we're putting in the bass if roots: roots_ = [int(Note(chord[0], octave=3)) for chord in chords_] chords_ = [[chord[1]]+chord[3:] for chord in chords_] # to create the shell voicing, let's first remove the root and 5th base_chords_ = [chord[:2] for chord in chords_] # keep the first two notes (3rd and 7th) if extensions: extensions_ = [chord[2:] for chord in chords_] # keep any higher extensions # we now perform simple voice leading on the base_chords_ (and then stick the extensions_ on top) chords_ = base_chords_ track = chords_to_track(chords_, durations) voiced_chords = [] for i, event in enumerate(track): chord = event[0][2] # current chord, to align with previous (if i>0) if extensions: chord_extensions = extensions_[i] if i == 0: voiced_chords.append([int(note) for note in chord]) if i>0: voiced_chords.append(smooth_next_chord(voiced_chords[i-1], chord)) # add extensions for each chord if extensions and len(chord_extensions)>0: chord_extensions = rebuild_chord_upwards([Note(ext) for ext in chord_extensions]) # to preserve ordering ext_shift = move_b_above_a_with_modularity(max(voiced_chords[i]),chord_extensions[0],12) - chord_extensions[0] # move first extension above base chord chord_extensions = [ext + ext_shift for ext in chord_extensions] # TO-DO build in other shell voicing extension options, see: # http://jamieholroydguitar.com/wp-content/uploads/2012/07/Shell-extentions1.png # this effectively captures 3 and 4-note voicings (http://www.thejazzpianosite.com/jazz-piano-lessons/jazz-chord-voicings/three-note-voicings/), possibly by limiting the number or priority of extensions voiced_chords[i] = voiced_chords[i] + chord_extensions if roots: voiced_chords[i] = [roots_[i]] + voiced_chords[i] voiced_chords = [[Note().from_int(int(note)) for note in chord] for chord in voiced_chords] return voiced_chords
def main(): window = curses.initscr() window.addstr(piano) frequency = st.Value(Note("C").to_hertz()) wave = st.Sin(frequency) envelope = st.ADSR(1, 0.1, 0.1, 0.7, 0.3) instrument = wave * envelope player = st.player.Player() player.start(instrument) try: curses.cbreak() curses.noecho() curses.curs_set(0) window.redrawwin() window.refresh() while True: c = chr(window.getch()) if c in piano_map: note = piano_map[c] frequency.set(note.to_hertz()) envelope.on() else: envelope.off() window.redrawwin() window.refresh() finally: curses.endwin()
def __init__(self, device, midi_time, note, velocity, on_off,channel): EventSignal.__init__(self, device, midi_time) self.note = Note().from_int(note) self.note.velocity = 127 self.note.channel = channel self.channel = channel self.on_off = on_off
def is_note(x): try: Note(x) return True except: print('bla') return False
def figGround(): # Purpose: Do a dictation of one instrument while other instruments are distracting in background. numnotes = setDuration() loopDictation = True while (loopDictation): randInstrument(1, set([ 0, 1, 2, 4, 6, 24, 25, 26, 27, 28, 29, 40, 41, 42, 56, 57, 60, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 78, 79, 80, 81, 82, 83, 85, 102, 103, 104, 105, 108, 109 ])) # Set lead/figure instr randInstrument(2, set([ 44, 45, 48, 49, 50, 51, 52, 53, 54, 55, 61, 62, 63, 86, 87, 88, 89, 90, 91, 92, 93 ])) # Set pad/ground instr randLeadNotes = [] for i in range(0, numnotes): randPitch = Note(12 * randint(3, 6) + randint(0, 12)) # randChord = randLeadNotes.append(randPitch) randBar = Bar() for n in randLeadNotes: randBar.place_notes(n, 4) playBeforeAnswer(randBar) print(randNotes) loopDictation = playAfterAnswer(randBar) print("\n")
def apply_individual_chord_voicing(chord:str, voicing_type=None, semitones=False, **kwargs): ''' Main handler for individual chord voicings. Expects a single chord shorthand e.g. 'C7'. Returns mingus Notes by default with option to return as semitone integers. ''' voiced_semitones = None if voicing_type is None: voiced_semitones = default_voice(chord) elif voicing_type == 'root': voiced_semitones = root_only_voice(chord) if voicing_type == 'shell': voiced_semitones = None elif voicing_type == 'rootless': voiced_semitones = rootless_voice(chord, **kwargs) if voiced_semitones is None: print(f'voicing_type {voicing_type} returned None for chord {chord}') voiced_semitones = default_voice(chord) # TO-DO: add_bass_note_to_slash_chord() (e.g. C7/E -> put an E in the bass) if not semitones: return [Note().from_int(semi) for semi in voiced_semitones] # list of mingus Notes else: return voiced_semitones # list of semitones
def root_only_voice(chord:str): ''' Expects a shorthand string like 'CM7' and will return with the root only (as semitone integer) ''' note_names = chords.from_shorthand(chord) # shorthand -> unpitched note strings ['C', 'E', 'G', 'B'] voiced_semitones = rebuild_chord_upwards([int(Note(note_names[0], octave=3))]) return voiced_semitones # ensure we voice from root upwards (in case e.g. everything defaulted to same octave)
def getScale(index, keySig, numberOfOctaves): switcher = { 0: scales.Aeolian(keySig), 1: scales.Bachian(keySig), 2: scales.Chromatic(keySig), 3: scales.Diatonic(keySig, (3,7)), 4: scales.Dorian(keySig), 5: scales.HarmonicMajor(keySig), 6: scales.HarmonicMinor(keySig), 7: scales.Ionian(keySig), 8: scales.Locrian(keySig), 9: scales.Major(keySig), 10: scales.MelodicMinor(keySig), 11: scales.MinorNeapolitan(keySig), 12: scales.Mixolydian(keySig), 13: scales.NaturalMinor(keySig), 14: scales.Octatonic(keySig), 15: scales.Phrygian(keySig), 16: scales.WholeTone(keySig) } scale = switcher.get(index, None) if scale is None: return None else: converted_scale = [] for i in range(numberOfOctaves): for note in scale.ascending(): #print note converted_scale.append(str(Note(note,4+i)).replace('-','').replace("'","")) return converted_scale
def addTrack(self, notes, duration=None): """ function to update track :param notes: array of notes to add :param duration: how long note should play for :return: none """ mingus_notes = [] for n in notes: if isinstance(n, int) == True: x = Note().from_int(n) mingus_notes.append(x) else: x = Note(n) mingus_notes.append(x) self.track.add_notes(mingus_notes, duration=duration)
def main(): fluidsynth.init('/usr/share/sounds/sf2/FluidR3_GM.sf2',"alsa") solution = [52,52,53,55,55,53,52,50,48,48,50,52,52,50,50] #testSol = [1,3,53,55,55,53,52,50,48,48,50,52,52,50,50] population = createInitialPopulation(250, len(solution)) #t = Track() #for note in findMostFit(population,solution): # t + note #fluidsynth.play_Track(t,1) generation = 1 highestFitness = calcFitness(findMostFit(population, solution), solution) print("Generation: 1") print("Initial Highest Fitness: " + str(highestFitness)) #print(calcFitness(testSol,solution)) while highestFitness < 1: population = createNewPopulation(population, solution, .01) generation = generation + 1 highestFitness = calcFitness(findMostFit(population, solution), solution) print("Generation: " + str(generation)) print("Highest Fitness level: " + str(highestFitness)) if generation % 10 == 0: print("hi") t = Track() for noteInt in findMostFit(population,solution): newNote = Note() newNote.from_int(noteInt) t + newNote fluidsynth.play_Track(t,1) #time.sleep(10) t = Track() for note in findMostFit(population,solution): t + note fluidsynth.play_Track(t,1)
def get_note(freq): """ Name: get_note Input: array, array of frequencies (freq) Output: str, the musical note Features: Finds the musical note corresponding to the given frequency """ from mingus.containers import Note freq.sort() #sorts the frequencies in ascending order freq = list(dict.fromkeys(freq)) #removes all duplicates from the list if len(freq) > 1: #list size is greater than 1 if freq[0] < 12: #first value in the list is less than 12 freq = freq[ 1:] #if there are more than 1 member in the list and the first value is less than 12 eliminate it #Below is a list of conditionals check to see if the minimum frequency is within a range, if it is note is equal to it's corresponding note value mfreq = min(freq) # calculate min frequency once if mfreq <= 15: note = 'REST' #if the frequency is less than 12 assume it was a Rest else: try: note = str(Note().from_hertz(mfreq)) except: note = 'Unknown' return (note) #return the found note
def load_from_song(self, song): ''' Fills a mingus-composition object with the data of a Song object ''' if 'bar_length' in song.info: try: self.bar_length = song.info['bar_length'] except: print "You need to specify length of a Bar first before you can do this" for line in song.lines: track = Track() bar = Bar() for segment in line.segments: if segment.type == 'pause': int_val = None elif segment.type == 'note': int_val = segment.pitch n = Note().from_int(int_val + 48) note_length = float(self.bar_length) / segment.duration if not bar.place_notes(n, note_length): track.add_bar(bar) bar = Bar() bar.place_notes(n, note_length) track.add_bar(bar) self.composition.add_track(track) self.path = song.path self.song_name = song.reader.file_name[:-4]
def play_word(word, synth, word_duration=0.01): # word_duration = 10 for note in word: n = Note(int(note['midi'])) n.velocity = int(note['vel']) fluidsynth.play_Note(n, channel=1) time.sleep(word_duration)
def note_collection(notes): ar = [] for note in notes: ar.append(Note(note)) return ar
def default_voice(chord:str): ''' Expects a shorthand string like 'CM7' and will return with the natural voicing of ascending extensions as semitones (integers) ''' note_names = chords.from_shorthand(chord) # shorthand -> unpitched note strings ['C', 'E', 'G', 'B'] voiced_semitones = rebuild_chord_upwards([int(Note(note)) for note in note_names]) return voiced_semitones # ensure we voice from root upwards (in case e.g. everything defaulted to same octave)
def get_notes_from_chord(self, chord='Cmaj7', octaves_above=0, octaves_below=0): notes = [] for n in chords.from_shorthand(chord): note = Note(n) notes.append(note) for i in xrange(octaves_above): note = Note(n) note.octave += i + 1 notes.append(note) for i in xrange(octaves_below): note = Note(n) note.octave -= i + 1 notes.append(note) return sorted(notes)
def __init__(self, key, Ioctave=None): self.key = key if not Ioctave: Ioctave = Note(key).octave self.Ioctave = Ioctave if key[0] == key[0].lower(): # natural minor self.rel_semitones = [0, 2, 3, 5, 7, 8, 10] self.keyname = key[0].upper + key[1:] + " Major" elif key[0] == key[0].upper(): # major self.rel_semitones = [0, 2, 4, 5, 7, 9, 11] self.keyname = key + " Minor" self.tonic = Note(name=key.upper(), octave=Ioctave) self.abs_semitones = [int(self.tonic) + x for x in self.rel_semitones] self.notes = [Note().from_int(x) for x in self.abs_semitones] self.numdict = dict([(k + 1, n) for k, n in enumerate(self.notes)])
def rebuild_chord_upwards(chord): chord = [int(Note(note)) for note in chord] # Note() to int a = chord[0] for i, b in enumerate(chord[1:]): b = move_b_above_a_with_modularity(a, b, 12) chord[i + 1] = b a = b return chord