def generate(self, length, bars, octave, scale=["C", "D", "E", "G", "A"], instrument=1, rand_length=False, time_signature=(4, 4), velocity=[64, 64], channel=1, rests=True, rule_number=30): # create the instrument for the main track instr = MidiInstrument() instr.instrument_nr = instrument # MIDI instrument number: http://www.midi.org/techspecs/gm1sound.php track = containers.Track(instr) self.set_instrument(instrument) if not self.initial: self.initial = [False] * 9 print "Error: initial set empty. Defaulting..." if rand_length: # start with quarter note as base length = 4 automata = Engine(rule_number, init_row=self.initial, edge_type=EdgeType.LOOP) # Index counting for diagnostics self.counts = dict((n, 0) for n in range(0, len(scale) * 2)) index = 5 # starting value for b in range(0, (length * bars) / 4): bar = Bar("C", time_signature) while bar.space_left() != 0: # runs until we're out of space for notes (e.g. complete bar) automata.step() # take a step index = self.get_chosen_note(index, automata.rows[-1]) if rand_length: # if we're randomly generating lengths of notes length = int(math.pow(2, random.randint(1, 4))) left = bar.space_left() space = ( (left - (left % 0.25)) * 16) if left > 0.25 else left * 16 # checks if we have enough space if space < 16 / length: length = int(16.0 / space) if rests and random.randint(0, 20) == 1: # same rest generation bar.place_rest(16) continue # skip the rest name = list(scale)[index if index < 5 else index - 4] # can be used for diagnostics self.counts[index] += 1 # add to count data self.notes.append(index) n = Note(name, octave=octave if index < 5 else octave + 1) n.set_velocity(random.randint(velocity[0], velocity[1])) # random velocity, can feel more "real" n.set_channel(channel) # if we want > 1 instruments we need > 1 channel bar.place_notes(n, length) # print self.format_block(automata.rows[-1]) track.add_bar(bar) # add bar to track self.track = track # set our track object to the newly generated track # for n in self.counts: # print str(n) + ": " + str(self.counts[n]) # diagnostics # print "=======" return self
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 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 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")
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 __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 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
class BassInstrument(Instrument): name = '' range = (Note('C', 0), Note('C', 10)) clef = 'Bass' def __init__(self, name): self.name = name Instrument.__init__(self)
def vector_to_midi(arr, filename="nice.midi"): track = Track() for note_arr in arr: note_num = int(np.argmax(note_arr)) note = Note() note.from_int(note_num - 3) track.add_notes(note) write_Track(filename, track) print("Done!")
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 play_basic_chord(chord): c = NoteContainer(chord) l = Note(c[0].name) l.octave_down() print ch.determine(chord)[0] # Play chord and lowered first note fluidsynth.play_NoteContainer(c) fluidsynth.play_Note(l) time.sleep(1.0) return c
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 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 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 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 __init__(self, noteContainer, bar, beat, duration): # assume the notecontainer has at least one note in it. self.bar = bar self.beat = beat self.duration = duration if noteContainer is None or len(noteContainer) == 0: self.is_rest = True self.name = 'Rest' self.octave = 0 else: self.is_rest = False note = noteContainer[0] Note.__init__(self, note)
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 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 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 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 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 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 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 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 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 note_collection(notes): ar = [] for note in notes: ar.append(Note(note)) return ar
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 playProgression(): progression = ["I", "vi", "ii", "iii7", "I7", "viidom7", "iii7", "V7"] key = "C" chords = progressions.to_chords(progression, key) if not fluidsynth.init(SF2): print "Couldn't load soundfont", SF2 sys.exit(1) while 1: i = 0 for chord in chords: c = NoteContainer(chords[i]) l = Note(c[0].name) p = c[1] l.octave_down() print ch.determine(chords[i])[0] # Play chord and lowered first note fluidsynth.play_NoteContainer(c) fluidsynth.play_Note(l) time.sleep(1.0) # Play highest note in chord fluidsynth.play_Note(c[-1]) # 50% chance on a bass note if random() > 0.5: p = Note(c[1].name) p.octave_down() fluidsynth.play_Note(p) time.sleep(0.50) # 50% chance on a ninth if random() > 0.5: l = Note(intervals.second(c[0].name, key)) l.octave_up() fluidsynth.play_Note(l) time.sleep(0.25) # 50% chance on the second highest note if random() > 0.5: fluidsynth.play_Note(c[-2]) time.sleep(0.25) fluidsynth.stop_NoteContainer(c) fluidsynth.stop_Note(l) fluidsynth.stop_Note(p) i += 1 print "-" * 20
def synthComm(): # print "I AM IN synthComm" timeStart = time.time() fluidsynth.init(config.sf2Path) note = Note() ser = serial.Serial(config.megaPath, config.megaBaud,timeout = 1) fluidsynth.stop_Note(note) while config.playing: info = ser.readline() print info if info is not '' and len(info) == 9: # print info # print timeStart fluidsynth.stop_Note(note) # print "---" # print len(info) # print "---" timeElp, x, y, vel = parseInput(timeStart, info) n = pos2Num(x,y) # print n # print names[n] note = Note(names[n],octave) note.velocity = vel fluidsynth.play_Note(note) print "-----" print "Time: {0} \nPosition: {1},{2}\n Velocity: {3}".format(timeElp, x, y, vel) print "-----" else: fluidsynth.stop_Note(note) # config.userHits = np.hstack((config.userHits, np.array([[time],[vel],[x],[y]))) # when done, close out connection ser.close() # print " I HAVE CLOSED THE connection" return
def play_chord(chord): c = play_basic_chord(chord) # Play highest note in chord fluidsynth.play_Note(c[-1]) # 50% chance on a bass note if random() > 0.5: p = Note(c[1].name) p.octave_down() fluidsynth.play_Note(p) time.sleep(0.50) # 50% chance on a ninth if random() > 0.5: p = Note(intervals.second(c[0].name, key)) p.octave_up() fluidsynth.play_Note(p) time.sleep(0.25) # 50% chance on the second highest note if random() > 0.5: fluidsynth.play_Note(c[-2]) time.sleep(0.25)
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)
def __repr__(self): name = Note.__repr__(self) return "<NoteNode %s, %d, %0.2f, %d>" % (name, self.bar, self.beat, self.duration)
def play_high_note(n): l = Note(n) l.octave_up() print l fluidsynth.play_Note(l) return l
def row_to_note_simple(self, row): base_note = 48 note = Note() note.from_int(row+base_note) return note
chorus = Track(ini).generate(8, BAR_NUMBER, 4, scale=scale1, rand_length=True, time_signature=time_sig, velocity=vel) song = Composition() trackmain = Track() # here is where you set the actual instrument print "Melody instrument: " + trackmain.set_instrument(instr).names[instr] + " ({})".format(instr) s = SongGen.Song() trackmain = s.generate(chorus, verse, bridge, trackmain.track) # LAST BAR b = Bar() n = Note('C', 4) n.set_channel(1) b.place_notes(n, 4) trackmain.add_bar(b) song.add_track(trackmain) # END MELODY # # BEGIN HARMONY # # setup verse ini = [False] * 5 ini[random.randint(0, 4)] = True # instr = random.randint(1, 104)
''' tester for mingus fluidsynth ''' from mingus.midi import fluidsynth from mingus.containers import Note import sys import time import random fluidsynth.init("../HS_Magic_Techno_Drums.SF2") names = ['A', 'Bb', 'B', 'C', 'Db','D','Eb', 'E', 'F', 'Gb','G','Ab'] # while(True): # n = Note(names[random.randrange(0,11,1)], random.randrange(1,4,1)) # n.velocity = random.randrange(40,100,1) # # fluidsynth.set_instrument(1, random.randrange(1,5,1), bank =1) # fluidsynth.play_Note(n) # time.sleep(.1*random.randrange(1,15,1)) # # fluidsynth.stop_Note(n) # time.sleep(.5*random.randrange(1,15,1)) # # fluidsynth.play_Note(n) for i in xrange(0,12): # for j in xrange(1,4): # n = Note(names[i],j) # fluidsynth.play_Note(n) # time.sleep(2) n = Note(names[i], 4) n.velocity = 127 fluidsynth.play_Note(n) time.sleep(1)
progression = ["I", "vi", "ii", "iii7", "I7", "viidom7", "iii7", "V7"] key = 'C' chords = progressions.to_chords(progression, key) if not fluidsynth.init(SF2): print "Couldn't load soundfont", SF2 sys.exit(1) while 1: i = 0 for chord in chords: c = NoteContainer(chords[i]) l = Note(c[0].name) p = c[1] l.octave_down() print ch.determine(chords[i])[0] # Play chord and lowered first note fluidsynth.play_NoteContainer(c) fluidsynth.play_Note(l) time.sleep(1.0) # Play highest note in chord fluidsynth.play_Note(c[-1]) # 50% chance on a bass note if random() > 0.5: p = Note(c[1].name)
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
chord_channel3 = 3 bass_channel = 4 solo_channel = 13 random_solo_channel = False if not fluidsynth.init(SF2): print "Couldn't load soundfont", SF2 sys.exit(1) chords = progressions.to_chords(progression, key) loop = 1 while loop < song_end: i = 0 if random_solo_channel: solo_channel = choice(range(5, 8) + [11]) for chord in chords: c = NoteContainer(chords[i]) l = Note(c[0].name) n = Note('C') l.octave_down() l.octave_down() print ch.determine(chords[i])[0] if not swing and play_chords and loop > chord_start and loop\ < chord_end: fluidsynth.play_NoteContainer(c, chord_channel, randrange(50, 75)) if play_chords and loop > chord_start and loop < chord_end: if orchestrate_second: if loop % 2 == 0: fluidsynth.play_NoteContainer(c, chord_channel2, randrange(50, 75)) else: fluidsynth.play_NoteContainer(c, chord_channel2, randrange(50,
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)