示例#1
0
 def play(self, events):
     notes_on = [e.to_ming_note() for e in events if e.command_type == 'NOTE_ON']
     notes_off = [e.to_ming_note() for e in events if e.command_type == 'NOTE_OFF']
     for note in notes_off:
         self.validator.add_gamer_note(note, 'NOTE_OFF')
     fluidsynth.stop_NoteContainer(NoteContainer(notes_off))
     for note in notes_on:
         self.validator.add_gamer_note(note, 'NOTE_ON')
     fluidsynth.play_NoteContainer(NoteContainer(notes_on))
示例#2
0
def play_offset(off, sleep_s=0.2, song=sonata, repeats=5, down_octaves=1, instrument=None):
        song = song * repeats
        if instrument is not None:
                for i in range(off):
                        fluidsynth.set_instrument(i+1, instrument)
        for i in range(len(song)+off):
                to_stop = i - off
                if to_stop >= 0:
                        fluidsynth.stop_NoteContainer(NoteContainer([a + "-" + str(int(b)-down_octaves) for (a, b) in song[to_stop].split()]), channel=(to_stop%off)+1)
                if i < len(song):
                        fluidsynth.play_NoteContainer(NoteContainer([a + "-" + str(int(b)-down_octaves) for (a, b) in song[i].split()]), channel=(i%off)+1, velocity=127)
                time.sleep(sleep_s)
示例#3
0
def resolve_chord_tone(chord, tone, Ioctave):
    # play_progression([numeral], st.KEY, Ioctave=Ioctave)

    if st.ALTERNATIVE_CHORD_TONE_RESOLUTION == 1:
        fluidsynth.play_NoteContainer(chord)
        play_wait()
        fluidsynth.play_Note(tone)
        play_wait()
        root = chord[0]
        interval = NoteContainer([root, tone])
        fluidsynth.play_NoteContainer(interval)
    elif st.ALTERNATIVE_CHORD_TONE_RESOLUTION == 2:
        fluidsynth.play_NoteContainer(chord)
        play_wait()
        tone_idx = [x for x in chord].index(tone)
        if tone_idx == 0:
            arpeggiate()
        elif tone_idx == 1:
            arpeggiate(invert=[1, 0, 2])
        elif tone_idx == 2:
            arpeggiate(descending=True)
        else:
            raise Exception("This chord tone resolutions mode is only "
                            "implemented for triads.")

        # fluidsynth.play_Note(Iup_note)
        # Iup_note = Note(st.KEY)
        # Iup_note.octave += 1
        # fluidsynth.play_Note(Iup_note)
    else:
        fluidsynth.play_NoteContainer(chord)
        play_wait()
        fluidsynth.play_Note(tone)
        play_wait()
        arpeggiate()  # sets NEWQUESTION = False
示例#4
0
    def play(self, melody, chords, bpm, scores, bars, key, mode, modeToPass,
             tra, file, out_dir):
        t2 = Track()
        sh = progressions.to_chords(chords, key)
        for i in range(0, len(sh)):
            b = Bar(None, (4, 4))
            if len(chords[i][0]) > 5:
                b.place_notes(None, 1)
            else:
                b.place_notes(NoteContainer(sh[i]), 1)
            t2 + b
        fluidsynth.pan(1, 25)
        fluidsynth.pan(2, 120)
        fluidsynth.main_volume(2, 50)
        fluidsynth.play_Tracks([melody, t2], [1, 2], bpm)

        # sleep(500000)

        button = Button(text='Clique para rearmonizar!',
                        command=lambda: self.checkReharmonize(
                            chords, scores, bars, key, mode, modeToPass, tra,
                            bpm, file, out_dir),
                        bg='brown',
                        fg='white',
                        font=('helvetica', 9, 'bold'))
        self.canvas1.create_window(200, 250, window=button)
示例#5
0
def eval_progression(ans, prog, prog_strums):
    try:
        int(ans)
        answers = [x for x in ans]
    except:
        answers = ans.split(" ")

    answers_correct = []
    for i, answer in enumerate(answers):
        try:
            correct_numeral = prog[i]
            tmp = progressions.to_chords([correct_numeral], st.KEY)[0]
            root = NoteContainer(tmp)[0].name
            user_correct = eval_single_chord(answer, correct_numeral, root)
            print(user_correct)
            answers_correct.append(user_correct)
        except IndexError:
            print("too many answers")
    if len(answers) < len(prog):
        print("too few answers")

    print("Progression:", " ".join(prog_strums))
    print("Your answer:   ", " ".join(answers))
    print("Correct Answer:",
          " ".join([str(st.NUMERALS.index(x) + 1) for x in prog]))

    if all(answers_correct):
        st.SCORE += 1
        print("Good Job!")
        print()
    else:
        print("It's ok, you'll get 'em next time.")
        print()
    # time.sleep(st.DELAY)
    play_wait()
示例#6
0
 def step(self, ticks):
     self.time += ticks
     new = [n for n in self.score.sounding_at(self.time) if not n in self.played]
     container = NoteContainer([note.fluidsynthname() for note in new])
     fluidsynth.play_NoteContainer(container)
     remove = [n for n in self.played if self.time >= n.delay + n.duration]
     self.played.difference_update(remove)
     self.played.update(new)
示例#7
0
def play_progression(prog, key, octaves=None, Ioctave=4, Iup="I", bpm=None):
    """ Converts a progression to chords and plays them using fluidsynth.
    Iup will be played an octave higher than other numerals by default.
    Set Ioctave to fall for no octave correction from mingus default behavior.
    """
    if octaves:
        assert len(prog) == len(octaves)

    if not octaves:
        I_chd = NoteContainer(progressions.to_chords([st.I], key)[0])
        I_chd[0].octave = Ioctave
        I_val = int(I_chd[0])

    chords = []
    for i, numeral in enumerate(prog):

        # find chords from numerals and key
        if numeral == "Iup":
            chord = NoteContainer(progressions.to_chords([Iup], key)[0])
        else:
            chord = NoteContainer(progressions.to_chords([numeral], key)[0])

        # Set octaves
        if octaves:
            d = octaves[i] - chord[0].octave
            for x in chord:
                x.octave += d
        elif Ioctave:  # make sure notes are all at least pitch of that 'I' root
            while int(chord[0]) > I_val:
                for x in chord:
                    x.octave_down()
            while int(chord[0]) < I_val:
                for x in chord:
                    x.octave_up()
        if numeral == "Iup":
            for x in chord:
                x.octave_up()

        chords.append(chord)

    easy_play(chords, bpm=bpm)
示例#8
0
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
示例#9
0
 def root2chord(root_pitch, type='triad'):
     """Given a `Note` object, returns a `NoteContainer`.  `type` determines
     the chord type and voicing."""
     if type == 'triad':
         tones = [1, 3, 5]
     elif type == 'sevenths':
         tones = [1, 3, 5, 7]
     elif type == 'triadbar':
         tones == [1, 5, 8, 10, 12, 15]
     else:
         tones = type
     degrees = [self.note2degree(root_pitch) + (d - 1) for d in tones]
     return NoteContainer(map(self.degree2note, degrees))
示例#10
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
def createMingusComposition(intermed, timesig, bIsTreble, bSharps):
    comp = Composition()
    comp.set_title('Trilled Results')
    comp.set_author('Author')
    if bIsTreble: ins = TrebleInstrument('')
    else: ins = BassInstrument('')

    track = Track(ins)
    track.name = 'Part 1'
    comp.add_track(track)

    assert len(timesig) == 2 and isinstance(timesig[0], int) and isinstance(
        timesig[1], int)
    firstbar = Bar(meter=timesig)
    track.add_bar(firstbar)

    mapDurs = {
        int(intermed.baseDivisions * 4): 1.0,  #whole note,
        int(intermed.baseDivisions * 2): 2.0,  #half note
        int(intermed.baseDivisions * 1): 4.0,  #qtr note, and so on
        int(intermed.baseDivisions * 0.5): 8.0,
        int(intermed.baseDivisions * 0.25): 16.0,
        int(intermed.baseDivisions * 0.125): 32.0,
        int(intermed.baseDivisions * 0.0625): 64.0,
    }

    for note in intermed.noteList:
        if note.pitch == 0 or note.pitch == (0, ):  # a rest
            thepitches = tuple()
        else:  # a note
            thepitches = []
            for pitch in note.pitch:
                pname, poctave = music_util.noteToName(pitch, bSharps)
                thepitches.append(pname + '-' + str(poctave))

        dur = note.end - note.start
        if dur not in mapDurs:
            raise NotesinterpretException('Unknown duration:' + str(dur))
        notecontainer = NoteContainer(thepitches)
        notecontainer.tied = note.isTied
        bFit = track.add_notes(notecontainer, mapDurs[dur])
        assert bFit

        #note that, naturally, will enforce having correct measure lines, since going across barline throughs exception

    return comp
示例#12
0
def createChord(freqList = [], volList = []):
	chord = NoteContainer()
	for i in range(0,len(freqList)):
		sel_freq = freqList[i]
		#scale the volumes of present frequencies
		if(sel_freq > 27 and sel_freq < 4186):
			new_Note = Note().from_hertz(sel_freq,440)
			if(sel_freq < 220 or sel_freq > 2500):
			 	if(sel_freq < 100 or sel_freq > 3000):
			 		volList[i] /= 1.4
			 	else:
			 		volList[i] /= 1.2
			new_Note.velocity = volList[i]
			if(len(BAR) > 0):
				#don't play repeat notes as quickly
				if not new_Note in (BAR[-1]):
					chord.add_note(new_Note)
	BAR.append(chord)
示例#13
0
def random_chord():
    # Pick random chord
    numeral = random.choice(st.NUMERALS)
    chord = NoteContainer(progressions.to_chords([numeral], st.KEY)[0])

    # Pick random octave, set chord to octave
    if st.MANY_OCTAVES:
        octave = random.choice(st.OCTAVES)
        d = octave - chord[0].octave
        for x in chord:
            x.octave = x.octave + d

        # Find Ioctave
        dist_to_tonic = (int(chord[0]) - int(Note(st.KEY))) % 12
        I_root = Note().from_int(int(chord[0]) - dist_to_tonic)
        Ioctave = I_root.octave
    else:
        Ioctave = st.DEFAULT_IOCTAVE
    return numeral, chord, Ioctave
示例#14
0
def interval_at_beat(track1, track2, beat, return_int=False):
    pitch1 = pitch_at_given_beat(track1, beat)
    pitch2 = pitch_at_given_beat(track2, beat)

    # Check for pauses
    if pitch1 is None or pitch2 is None:
        return None

    # Return halftone interval if requested
    interval_halftones = Note(pitch1[0]).measure(Note(pitch2[0]))
    if return_int == True:
        return interval_halftones

    # Else return a str
    # Workaround for the fact that the .determine function doesn't return unisons or octaves
    if interval_halftones == 0:
        return 'perfect unison'
    elif interval_halftones % 12 == 0:
        return 'octave'
    else:
        note_pair = NoteContainer([pitch1[0], pitch2[0]])
        return note_pair.determine()[0]
示例#15
0
def generate_track(g, n, name):
    root = np.random.randint(0, n)
    edges = nx.bfs_edges(g.G, root)
    nodes = [root] + [v for u, v in edges]
    m = MidiInstrument(4)
    t = Track()
    track = []
    t.instrument = m
    nNotes = 0
    print("##### Creating Tracks")
    for x in nodes:
        value = t.add_notes(NoteContainer(g.G.nodes[x]["note"]),
                            g.G.nodes[x]["duration"])
        t.bars[-1].set_meter((n, 1))
        track.append(g.G.nodes[x]["note"])
        nNotes = nNotes + 1
    print("##### Notes Generated:")
    print(*t)
    print("##### Number of notes:")
    print(nNotes)
    midi_file_out.write_Track(name + ".mid", t)
    return t
示例#16
0
 def getChordOrArpeggio(self, input_bar):
     notes = input_bar.get_note_names()
     random.seed()
     chord = chords.major_triad(notes[random.randint(0,len(notes) - 1)])
     new_bar = Bar()
     #nc = NoteContainer(chord)
     #new_bar.place_notes(nc, 1)
     #return new_bar
     if(len(notes) % 2 != 0):
         #this will be a chord
         nc = NoteContainer(chord)
         new_bar.place_notes(nc, 1)
         return new_bar
     else:
         #this will be an arpeggio
         duration = 0
         print(str(len(chord)))
         for note in chord:
             if(duration == 0):
                 duration = 2
             else:
                 duration = 4
             new_bar.place_notes(note, duration)
         return new_bar
示例#17
0
def export(melody_track, chords, key, time_sig, bpm, file):
    i = Instrument()
    i.instrument_nr = 1
    t2 = Track()
    for i in range(0, len(chords)):
        b = Bar(key, time_sig)
        if len(chords[i][0]) > 5:
            b.place_notes(None, 1)
        else:
            b.place_notes(NoteContainer(chords[i]), 1)
        t2 + b

    c = Composition()
    c.add_track(melody_track)
    c.add_track(t2)

    out_dir = 'out'

    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    mid = file.split('/')[-1]
    if os.path.exists(out_dir + '/' + mid):
        os.remove(out_dir + '/' + mid)
    MidiFileOut.write_Composition(out_dir + '/' + mid, c, bpm)

    file = out_dir + '/' + mid

    sys.argv.append('')
    sys.argv.append('')

    sys.argv[1] = "--midi-file=" + file
    sys.argv[2] = "--out-dir=" + out_dir

    midi.main()
    if os.path.exists(file):
        os.remove(file)
示例#18
0
    def interval(self, number, root=None, ascending=True):
        assert number > 0
        if not root:
            root = self.notes[0]

        root_num = self.note2num(root)
        if ascending:
            second_note_num = (self.note2num(root) + (number - 1)) % 7
            if second_note_num == 0:
                second_note_num = 7
            semi_dist = self.nums2semidist(root_num, second_note_num)
            if second_note_num < root_num:
                semi_dist = 12 - semi_dist
            second_note_int = int(root) + semi_dist + 12 * ((number - 1) // 7)
        else:
            second_note_num = (self.note2num(root) - (number - 1)) % 7
            if second_note_num == 0:
                second_note_num = 7
            semi_dist = self.nums2semidist(root_num, second_note_num)
            if second_note_num > root_num:
                semi_dist = 12 - semi_dist
            second_note_int = int(root) - semi_dist - 12 * ((number - 1) // 7)

        return NoteContainer(sorted([root, Note().from_int(second_note_int)]))
示例#19
0
def init_preset_track(num):
    track = Track()
    if num == 1:  #C-chord
        track.add_notes(None)
        track.add_notes(None)
        nc = NoteContainer(["C", "E"])
        track.add_notes(nc)
        track + "E-5"
        track + "A-3"
        track.add_notes(None)
        track + "C-5"
        track + "E-5"
        nc2 = NoteContainer(["F", "G"])
        track.add_notes(nc2)
        track + "G-5"
        track + "C-6"
    if num == 2:
        track + "E"
        track + "D"
        track + "E"
        track + "A-2"
        track + "C"
        track + "D"
        track + "E"
        track + "F-5"
        track + "D"
        track + "E"
        track + "E-5"
    if num == 3:
        test_scale = scales.Major("C")
        for i in range(7):
            track + test_scale[i]
    if num == 4 or num == 'blinka':
        bar = Bar()
        bar.place_notes('C-4', 8)
        bar.place_notes('C-4', 8)
        bar.place_notes('G-4', 8)
        bar.place_notes('G-4', 8)
        bar.place_notes('A-4', 8)
        bar.place_notes('A-4', 8)
        bar.place_notes('G-4', 4)
        track.add_bar(bar)

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

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

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

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

    if num == "panther":  #Scale E
        track.add_notes('D#-4', 8)
        track.add_notes('E-4', 8 / 3)
        track.add_notes('F#-4', 8)
        track.add_notes('G-4', 8 / 3)
    return track
示例#20
0
    def MIDI_to_Composition(self, file):
        (header, track_data) = self.parse_midi_file(file)
        c = Composition()
        if header[2]['fps']:
            print("Don't know how to parse this yet")
            return c
        ticks_per_beat = header[2]['ticks_per_beat']
        for track in track_data:
            t = Track()
            b = Bar()
            metronome = 1  # Tick once every quarter note
            thirtyseconds = 8  # 8 thirtyseconds in a quarter note
            meter = (4, 4)
            key = 'C'
            for e in track:
                (deltatime, event) = e
                duration = float(deltatime) / (ticks_per_beat * 4.0)
                if duration != 0.0:
                    duration = 1.0 / duration
                if deltatime != 0:
                    if not b.place_notes(NoteContainer(), duration):
                        t + b
                        b = Bar(key, meter)
                        b.place_notes(NoteContainer(), duration)

                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)
示例#21
0
def generate_accompaniment(net_output_chords):
    generated_chords = []
    chords = []
    for chord in net_output_chords:
        root, key = (chord.split(":"))
        print(root, key)
        if key == 'maj':
            chords.append(ch.major_triad(root))
        if key == 'min':
            chords.append(ch.minor_triad(root))      

    print(chords)  

    key = chords[0][0]
    print('key', key)
    if not fluidsynth.init(SF2):
        print("Couldn't load soundfont", SF2)
        sys.exit(1)

    print(dir(fluidsynth.midi))
    # fluidsynth.midi.start_audio_output()
    fluidsynth.midi.start_recording()
    phrase = 0
    while phrase == 0:
        i = 0
        for chord in chords:
            print("chord", chord)
            c = NoteContainer(chords[i])
            generated_chords.append([{'note':cc.name.replace("B#","B").replace("E#","E").replace("##","#"), 'octave':cc.octave} for cc in c])
            l = Note(c[0].name)
            p = c[1]
            l.octave_down()
            print(ch.determine(chords[i])[0])

            # Play chord and lowered first note
            # fluidsynth.midi.MidiFileOut.write_NoteContainer("test.mid", c)
            print("NEW CHORD = ", c)

            if PLAY_ENABLED:

                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.50:
                    p = Note(c[1].name)
                    p.octave_down()
                    fluidsynth.play_Note(p)
                time.sleep(0.50)

                # 50% chance on a ninth

                if random() > 0.50:
                    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.50:
                    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)
        phrase = 1
        return generated_chords
示例#22
0
def new_question_chord_tone():
    if st.NEWQUESTION:
        if st.COUNT:
            print("score: {} / {} = {:.2%}".format(st.SCORE, st.COUNT,
                                                   st.SCORE / st.COUNT))
        st.COUNT += 1

        # Pick random chord/octave
        numeral, chord, Ioctave = random_chord()

        # Pick a random tone in the chord
        tone = random.choice(chord)

        # store question info
        st.CURRENT_Q_INFO = {
            'numeral': numeral,
            'chord': chord,
            'Ioctave': Ioctave,
            'tone': tone
        }
    else:
        numeral = st.CURRENT_Q_INFO['numeral']
        chord = st.CURRENT_Q_INFO['chord']
        Ioctave = st.CURRENT_Q_INFO['Ioctave']
        tone = st.CURRENT_Q_INFO['tone']

    # Play chord, then tone
    def playfcn():
        play_progression([numeral], st.KEY, Ioctave=Ioctave)
        play_wait()
        fluidsynth.play_Note(tone)

    p = Process(target=playfcn())
    p.start()

    # Request user's answer
    mes = ("Which tone did you hear?\n"
           "Enter {}, or {}: ".format(
               ", ".join([str(t) for t in st.TONES[:-1]]), st.TONES[-1]))
    ans = getch(mes).strip()
    p.terminate()

    if ans in menu_commands:
        menu_commands[ans].action()
    else:
        try:
            ans = int(ans)
        except:
            print("User input not understood.  Please try again.")
            st.NEWQUESTION = False

        if ans in st.TONES:
            tone_idx = [n for n in chord].index(tone)
            correct_ans = st.TONES[tone_idx]
            if ans == correct_ans:
                st.SCORE += 1
                print("Yes! The {} tone of".format(correct_ans),
                      chordname(chord, numeral))
                if st.ARPEGGIATE_WHEN_CORRECT:
                    resolve_chord_tone(chord, tone, Ioctave)
                    play_wait()
                    st.NEWQUESTION = True
            else:
                print("No! The {} tone of".format(correct_ans),
                      chordname(chord, numeral))
                if st.ARPEGGIATE_WHEN_INCORRECT:
                    resolve_chord_tone(chord, tone, Ioctave)
                    play_wait()
                    st.NEWQUESTION = True

        # secret option
        elif ans in [8, 9, 0]:
            tone_idx = [8, 9, 0].index(ans)
            for num in st.NUMERALS:
                tmp = progressions.to_chords([num], st.KEY)[0]
                num_chord = NoteContainer(tmp)
                play_progression([num], st.KEY, Ioctave=Ioctave)
                play_wait()
                fluidsynth.play_Note(num_chord[tone_idx])
                play_wait()
            play_wait()
            st.NEWQUESTION = False

        else:
            print("User input not understood.  Please try again.")
            st.NEWQUESTION = False
    return
示例#23
0
            gypsy_bar.place_rest(duration=duration)
        else:
            gypsy_bar.place_notes(note, duration=duration)
print(gypsy_bar)
midi_file_out.write_Bar("gypsy_bar_" + version + ".mid", gypsy_bar)
gypsy_track.add_bar(gypsy_bar)

print(gypsy_track)

drum_track = Track()
kick = drums["kick"]
snare = drums["snare"]
hat = drums["hatclosed"]
# for dbar in range(0, 20):
drum_bar = Bar()
drum_bar.place_notes(NoteContainer([kick, hat]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
drum_bar.place_notes(NoteContainer([kick, hat, snare]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
drum_bar.place_notes(NoteContainer([kick, hat]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
drum_bar.place_notes(NoteContainer([kick, hat, snare]), value.eighth)
drum_bar.place_notes(hat, value.eighth)
drum_track.add_bar(drum_bar)

midi_file_out.write_Bar("drum_bar_" + version + ".mid", drum_bar)

print(drum_track)

# song = Composition()
# song.add_track(gypsy_track)
示例#24
0
def new_question_interval():
    if st.NEWQUESTION:
        if st.COUNT:
            print("score: {} / {} = {:.2%}"
                  "".format(st.SCORE, st.COUNT, st.SCORE / st.COUNT))
        st.COUNT += 1

        # Pick Ioctave
        if st.MANY_OCTAVES:
            Ioctave = random.choice(st.OCTAVES)
        else:
            Ioctave = st.DEFAULT_IOCTAVE

        from musictools import Diatonic
        diatonic = Diatonic(key=st.KEY, Ioctave=Ioctave)

        # pick first note
        if st.FIXED_ROOT:
            first_note = diatonic.notes[st.FIXED_ROOT - 1]
        else:
            first_note = random.choice(diatonic.notes)

        # pick second note
        if st.INTERVAL_MODE == 'triads':
            number = random.choice([3, 5, 8])
            interval = diatonic.interval(number,
                                         root=first_note,
                                         ascending=True)
        elif st.INTERVAL_MODE == 'sevenths':
            number = random.choice([3, 5, 7, 8])
            interval = diatonic.interval(number,
                                         root=first_note,
                                         ascending=True)
        elif st.INTERVAL_MODE == 'ascending':
            number = random.choice(st.INTERVALS)
            interval = diatonic.interval(number,
                                         root=first_note,
                                         ascending=True)
        elif st.INTERVAL_MODE == 'descending':  # redundant for harmonic intrvls
            number = random.choice(st.INTERVALS)
            interval = diatonic.interval(number,
                                         root=first_note,
                                         ascending=False)
        elif st.INTERVAL_MODE == 'mixed':  # redundant for harmonic intervals
            number = random.choice(st.INTERVALS)
            interval = diatonic.interval(number,
                                         root=first_note,
                                         ascending=bool(random.choice([0, 1])))
        else:
            raise Exception("Can't understand.  st.INTERVAL_MODE = {}"
                            "".format(st.INTERVAL_MODE))

        # change Unison intervals to P8 intervals
        if len(interval) == 1:
            P8 = copy(interval[0])
            P8.octave += 1
            interval = NoteContainer([interval[0], P8])

        # store question info
        st.CURRENT_Q_INFO = {
            'interval': interval,
            'Ioctave': Ioctave,
            'diatonic': diatonic
        }

    else:
        interval = st.CURRENT_Q_INFO['interval']
        Ioctave = st.CURRENT_Q_INFO['Ioctave']
        diatonic = st.CURRENT_Q_INFO['diatonic']

    # Play interval
    if st.HARMONIC_INTERVALS:
        easy_play(interval)
    else:
        easy_play([x for x in interval])

    # Request user's answer
    ans = input("Enter 1-7 or note names separated by spaces: ").strip()

    if ans in menu_commands:
        menu_commands[ans].action()
    else:
        if st.NAME_INTERVAL:
            eval_interval_name(ans, interval, diatonic)
        else:
            eval_interval(ans, interval, diatonic)
    return
示例#25
0
height = TARGET_HEIGHT - 2 * y_offset - 60  # remove torso
width = TARGET_WIDTH - 2 * x_offset

cam = cv2.VideoCapture(0)

detect_timer = 0
DETECT_WAIT = 9

has_user = False
has_user_counter = 0
has_user_timeout = 0
HAS_USER_WAIT = 50

BASE_OCTAVE = 5
base_note = int(Note('C', BASE_OCTAVE))
notes = NoteContainer()

NOTE_COUNT = 6
NOTE_SPACING = 3
for offset in range(0, NOTE_SPACING * NOTE_COUNT, NOTE_SPACING):
    note = Note().from_int(base_note + offset)
    note.next_octave = offset >= 12
    notes += note

eyes = cv2.CascadeClassifier('haarcascade_eye.xml')

if cam.isOpened():
    while True:
        ret, frame = cam.read()
        frame = cv2.resize(frame, (TARGET_WIDTH, TARGET_HEIGHT))
        frame = frame[y_offset:y_offset + height, x_offset:x_offset + width]
示例#26
0
    fluidsynth.init('GeneralUser GS v1.471.sf2', 'alsa')
else:
    fluidsynth.init('GeneralUser GS v1.471.sf2')

fluidsynth.set_instrument(1, int(sys.argv[1]), int(sys.argv[2]))

c = Note("C-4")
e = Note("E-4")
g = Note("G-4")

fluidsynth.play_Note(c)
time.sleep(2)

fluidsynth.play_Note(e)
time.sleep(2)

fluidsynth.play_Note(g)
time.sleep(2)

fluidsynth.stop_Note(c)
fluidsynth.stop_Note(e)
fluidsynth.stop_Note(g)
time.sleep(2)

nc = NoteContainer(["C-4", "E-4", "G-4"])
nc.velocity = 70
fluidsynth.play_NoteContainer(nc)
time.sleep(2)

fluidsynth.stop_NoteContainer(nc)
示例#27
0
chord_channel2 = 7
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:
示例#28
0
def main(hMidi, file):

    c2 = MidiFileIn.MIDI_to_Composition(file)

    out_dir = 'out'

    tra = Track()
    notes = list()
    bars = []
    for x in c2:
        if (x.__class__.__name__ == "Composition"):
            for track in x.tracks:
                i = 0
                for bar in track.bars:
                    notesB = []
                    if len(bar.get_note_names()) == 0:
                        bar.empty()
                        bar.place_rest(1)
                        tra + bar
                        notesB.append(None)
                        bars.append(notesB)
                        i = i + 1
                        continue
                    tra + bar
                    for y in bar:
                        if (len(NoteContainer(y[-1]).get_note_names()) > 0):
                            notes.append(
                                NoteContainer(y[-1]).get_note_names()[0])
                            notesB.append((y[2][0].name, y[2][0].octave))
                    bars.append(notesB)
                    i = i + 1

    bars = bars[:-1]
    tra.bars = tra.bars[:-1]
    bpm = c2[1]

    ### DESCOBRIR TONALIDADE MELODIA -> 1o GRAU ###
    key_and_mode = scales.determine(notes)[0]
    if key_and_mode != None:
        key = key_and_mode.split(" ")[0]
        mode = key_and_mode.split(" ")[1]

    score = converter.parse(file)
    parse = score.analyze('key')
    keym = parse.tonic.name
    modem = parse.mode

    flag = False
    if mode == ('harmonic' or 'minor'):
        key = keys.relative_major(key.lower())
        mode = 'major'
        flag = True
    elif mode != modem:
        Flag = True

    scores = {
        'I': {
            0: 0.5,
            1: -0.2,
            2: 0,
            3: 0,
            4: 0.35,
            5: 0,
            6: 0,
            7: 0.35,
            8: 0,
            9: 0,
            10: 0,
            11: 0.1
        },
        'ii': {
            0: 0,
            1: 0.1,
            2: 0.5,
            3: -0.2,
            4: 0,
            5: 0,
            6: 0.35,
            7: 0,
            8: 0,
            9: 0.35,
            10: 0,
            11: 0
        },
        'iii': {
            0: 0,
            1: 0,
            2: 0,
            3: 0.1,
            4: 0.5,
            5: -0.2,
            6: 0,
            7: 0,
            8: 0.35,
            9: 0,
            10: 0,
            11: 0.35
        },
        'IV': {
            0: 0.35,
            1: 0,
            2: 0,
            3: 0,
            4: 0.1,
            5: 0.5,
            6: -0.2,
            7: 0,
            8: 0,
            9: 0.35,
            10: 0,
            11: 0
        },
        'V': {
            0: 0,
            1: 0,
            2: 0.35,
            3: 0,
            4: 0,
            5: 0,
            6: 0.1,
            7: 0.5,
            8: -0.2,
            9: 0,
            10: 0,
            11: 0.35
        },
        'vi': {
            0: 0,
            1: 0.35,
            2: 0,
            3: 0,
            4: 0.35,
            5: 0,
            6: 0,
            7: 0,
            8: 0.1,
            9: 0.5,
            10: -0.2,
            11: 0
        },
        'vii': {
            0: -0.2,
            1: 0,
            2: 0,
            3: 0.35,
            4: 0,
            5: 0,
            6: 0.35,
            7: 0,
            8: 0,
            9: 0,
            10: 0.11,
            11: 0.5
        }
    }

    scoresMin = {
        'I': {
            0: 0,
            1: 0.35,
            2: 0,
            3: 0,
            4: 0.35,
            5: 0,
            6: 0,
            7: 0,
            8: 0.1,
            9: 0.5,
            10: -0.2,
            11: 0
        },
        'ii': {
            0: -0.2,
            1: 0,
            2: 0,
            3: 0.35,
            4: 0,
            5: 0,
            6: 0.35,
            7: 0,
            8: 0,
            9: 0,
            10: 0.11,
            11: 0.5
        },
        'iii': {
            0: 0.5,
            1: -0.2,
            2: 0,
            3: 0,
            4: 0.35,
            5: 0,
            6: 0,
            7: 0.35,
            8: 0,
            9: 0,
            10: 0,
            11: 0.1
        },
        'IV': {
            0: 0,
            1: 0.1,
            2: 0.5,
            3: -0.2,
            4: 0,
            5: 0,
            6: 0.35,
            7: 0,
            8: 0,
            9: 0.35,
            10: 0,
            11: 0
        },
        'V': {
            0: 0,
            1: 0,
            2: 0,
            3: 0.1,
            4: 0.5,
            5: -0.2,
            6: 0,
            7: 0,
            8: 0.35,
            9: 0,
            10: 0,
            11: 0.35
        },
        'vi': {
            0: 0.35,
            1: 0,
            2: 0,
            3: 0,
            4: 0.1,
            5: 0.5,
            6: -0.2,
            7: 0,
            8: 0,
            9: 0.35,
            10: 0,
            11: 0
        },
        'vii': {
            0: 0,
            1: 0,
            2: 0.35,
            3: 0,
            4: 0,
            5: 0,
            6: 0.1,
            7: 0.5,
            8: -0.2,
            9: 0,
            10: 0,
            11: 0.35
        }
    }

    if flag:
        scores = scoresMin

    modeToPass = '******' if flag else 'major'
    chords = Harmonizer.harmonize(bars, key, scores, (4, 4), modeToPass)

    label1 = Label(hMidi.root, text='Harmonizando!')
    label1.config(font=('helvetica', 14))
    hMidi.canvas1.create_window(200, 100, window=label1)

    pg = Progressbar(hMidi.root,
                     orient=HORIZONTAL,
                     length=100,
                     mode='determinate')
    pg['maximum'] = 230
    pg['value'] = 0
    hMidi.pg = pg
    hMidi.canvas1.create_window(200, 140, window=pg)

    hMidi.updt('')
    label4 = Label(hMidi.root, textvariable=hMidi.labelText)
    hMidi.canvas1.create_window(200, 160, window=label4)

    hMidi.update(0)

    fluidsynth.init("Sounds/soundfont.sf2", "alsa")

    button1 = Button(
        text='Ouvir resultado',
        command=lambda: hMidi.play(tra, chords, bpm, scores, bars, key, mode,
                                   modeToPass, tra, file, out_dir),
        bg='brown',
        fg='white',
        font=('helvetica', 9, 'bold'))
    hMidi.canvas1.create_window(200, 200, window=button1)
    if hMidi.exp:
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        Harmonizer.export(tra, progressions.to_chords(chords, key), key,
                          (4, 4), bpm, file)

    if hMidi.sheet:
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        Harmonizer.to_Sheet(bars, progressions.to_chords(chords, key), tra,
                            key, mode, file, out_dir, hMidi.name, hMidi.author)
示例#29
0
#音对象方法
int(n)  #音对象的数值
c = Note()
c.from_int(12)  #使用数值创建音对象
c.octave_up()  #升八度
c.octave_down()  #降八度
c.change_octave(2)  #升n八度
c.transpose('3', up=True)  #向上升三度
c.augment()  #升半音
c.diminish()  #降半音
c.remove_redundant_accidentals()  #清理多余升降号(只能成对清理,烂)

#谱容器
from mingus.containers import NoteContainer
#创建谱容器对象(继承列表,完全可以按列表操作,不用看下面的)
n = NoteContainer(['A-3', 'C-5', 'B-4'])
n.add_note('F-1')  # 0位加音
n.remove_note('B', 4)  #删音
n.empty()  #清空

#乐器音色
from mingus.containers.instrument import Instrument, Piano, Guitar
#创建乐器对象
i = Instrument()
i.range  #乐器音域
i.set_range((Note('C-2'), Note('E-4')))  #设定音域
i.note_in_range('F-4')  #判断音是否在乐器音域内
#音轨
from mingus.containers import Track
t = Track(i)  #乐器放入音轨容器
示例#30
0
builtChords = progressions.to_chords(flatList, key)

## Create bars for each chord
comp = []
lead = []

for chord in builtChords:
    modChord = chord

    #randomly invert before adding
    if random() > 0.7:  # and randVal < 0.8:
        modChord = chords.second_inversion(modChord)
    elif random() > 0.7:
        modChord = chords.third_inversion(modChord)

    container = NoteContainer(modChord)

    #write a melody
    leadBar = Bar(key, meter)
    noteLengths = [2, 4, 8]
    lastNote = Note()
    lastNoteLength = 4

    while leadBar.is_full() == False:
        if random() < 0.8:
            currentBeat = leadBar.current_beat
            # add a note
            # if random() < 0.5 and len(leadBar) > 0:
            #     n = Note(intervals.second(lastNote.name, key))
            #     print("second of last")
            if random() < 0.5 and currentBeat != 0.0: