示例#1
0
    def display_progression(self, nop=None):
        s = []
        pr = self.get_progression(self.progression)
        for ch in progressions.to_chords(pr, self.get_key()):
            c = NoteContainer(ch)
            s.append(c.determine(True)[0])

        self.prog_var.set( '  '.join( s ) )
        self.uniprog_var.set('  '.join( pr ))
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
示例#3
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 xrange(abs(sharps)):
                            if sharps < 0:
                                key = intervals.major_fourth(key)
                            else:
                                key = intervals.major_fifth(key)
                        b.key = Note(key)
                    else:
                        print 'Unsupported META event', event['meta_event']
                else:
                    print 'Unsupported MIDI event', event
            t + b
            c.tracks.append(t)
        return (c, bpm)
    '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])
示例#5
0
]
downbeatpossiblevalues = [
    0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0,
    3.25, 3.5, 3.75, 4.0
]
possiblenote = ["C", "D", "E", "F", "G", "A", "B"]
initialized = False
uiplayer = FluidSynthSequencer()
fluidsynth.init('goodtry.sf2', uiplayer)
cymbal = Note()
cymbal.from_int(37)
snare = Note()
snare.from_int(26)
highhat = Note()
highhat.from_int(30)
base = NoteContainer()
basenote = Note()
basenote.from_int(23)
base.add_note(basenote)
soundtrack = Track()
starttrack = Track()
starttrack.add_notes(highhat, 1)
starttrack.add_notes(highhat, 1)
starttrack.add_notes(highhat, 1)
starttrack.add_notes(highhat, 1)

for i in range(0, 32):
    if math.floor(i / 4.0) == i / 4.0:
        soundtrack.add_notes([basenote, cymbal], 1.0)
    else:
        soundtrack.add_notes(base, 1.0)
示例#6
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)
示例#7
0
def read_notes(fn, notes):
    with open(fn) as f:
        content_lines = f.readlines()
    content = []
    for line in content_lines:
        if not (line.startswith('#')):
            content.extend(line.split())
        elif (line.startswith('### ')):
            meta = line[4:]
            var, val = meta.split(':')
            print(var + '\t' + val)

#
# loop through content, computing start and end events
#
    currtime = 0
    tie_forward = False
    for line in content:
        tie_backward = tie_forward
        tie_forward = False

        if line[:4] in "<key:":  # get key for interpreting chords
            #           print "key:", line[5:-1], "keylet:", line[5:6]
            nkey = pitch_class_dict[line[5:6]]
            key = line[5:-1]
            if key[-1] == 'm':
                key = key.lower()
#               key=key[:-1].lower()
#           print "key:", key, "nkey:", nkey

        if line[0] in "<":  # skip tags such as <sot>, <eot>, <time>, <bar>
            continue


#       print("line:", line)
        note, duration = line.split(":")

        if duration.endswith('t'):
            tie_forward = True
            duration = duration[:-1]

        try:
            dnum, ddenom = duration.split("/")
            duration_num = float(dnum) / float(ddenom)
        except:
            duration_num = int(duration)

        if note[0] in "ABCDEFG":
            n = NoteContainer(Note(note))

            velocity = velocity_normal
            if tie_backward:
                velocity = velocity_slur

            notes.append([currtime, n, "S", velocity])
            notes.append([currtime + duration_num, n, "E"])
            currtime += duration_num
        elif note == "rest":
            currtime += duration_num
        elif note == "backup":
            currtime = currtime - duration_num
        elif note == "forward":
            currtime = currtime + duration_num

        #
        # roman numeral chords, e.g. rchord-viidim7:1
        #
        elif "rchord" in note:  # roman numeral chord such as I, IV
            x, c = note.split('-')
            simple_c = simplify_chord(c)
            log("rchord: " + c + "\tsimple: " + simple_c + "\tkey:" + key)
            progression = progressions.to_chords([simple_c], key)
            chord = NoteContainer(progression[0])
            notes.append([currtime, chord, "S", velocity_chord])
            notes.append([currtime + duration_num, chord, "E"])
            currtime += duration_num

        #
        # numeric chord, e.g. nchord-145 = tonic (1) + third (16) + fifth (128)
        #
        elif "nchord" in note:
            x, c = note.split('-')
            #           print "--chord:", c, "key:", key
            nc = int(c)
            n = 0
            while nc > 0:
                if nc & 1:
                    note = note_dict[(n + nkey) % 12]
                    #                   print "  --note", note
                    notes.append(
                        [currtime, [n + nkey + 48], "S", velocity_chord])
                    notes.append(
                        [currtime + duration_num, [n + nkey + 48], "E"])
                n += 1
                nc = nc // 2
            currtime += duration_num

        elif "chord" in note:  # chord such as Am7
            x, c = note.split('-')
            chord = NoteContainer(chords.from_shorthand(c))
            notes.append([currtime, chord, "S", velocity_chord])
            notes.append([currtime + duration_num, chord, "E"])
            currtime += duration_num
        else:
            print "Illegal music token item:", note
示例#8
0
    0.875: value.dots(2),  #Round to dotted half
    0.9375: value.dots(2),  #Round to dotted half                
    1: 1
})
df["Diff"] = df["Diff"].map(LengthToNote)  #Map to note values for Mingus

display(df.head(10))

#Creating tracks --- Left
t_l = Track()
for i in set(df["Measure"].unique()[:-1]):
    b = Bar(key=keysig)
    subset = df[df["Measure"] == i]
    for j, k in zip(subset["Notes_l"], subset["Diff"]):
        if len(j) > 0:  #If note is not NaN
            nc = NoteContainer(j)  #Define the note
            b.place_notes(nc, k)  #Add note to bar with length
        else:
            b.place_notes(
                None,
                k)  #Place a rest note the lenght of the other hand's note
    t_l + b
LithHarbor_ly_left = LilyPond.from_Track(t_l)  #Create .ly file

#Creating tracks --- right
t_r = Track()
for i in set(df["Measure"].unique()[:-1]):
    b = Bar(key=keysig)
    subset = df[df["Measure"] == i]
    for j, k in zip(subset["Notes_r"], subset["Diff"]):
        if j:  #If note is not NaN
示例#9
0
        2: ["Eb", 381, 340],
        3: ["F", 421, 340],
        4: ["Gb", 421, 381],
        5: ["Ab", 421, 421],
        6: ["Bb", 381, 421],
        7: ["C", 340, 421],
        8: ["Db", 340, 381],
    }
    return switcher.get(argument)


###############################################
### START of main

# create NoteContainer
n = NoteContainer()
n_1 = NoteContainer()
n_2 = NoteContainer()

# initialize synth
fluidsynth.init("/usr/share/sounds/sf2/FluidR3_GM.sf2", "alsa")
fluidsynth.set_instrument(1, 108)
fluidsynth.set_instrument(2, 53)
fluidsynth.set_instrument(3, 112)

for step in range(16, 100):
    """ fluidsynth.play_Note(64, 0, 100)
    sleep(1)
    fluidsynth.stop_Note(64, 0) """
    print("zoom x", 2**step)
    rate = 2**step
示例#10
0
	print RED + "@ Pyfpiano.py" + DEFAULT + " version 0.1"
	print YELLOW + "@ author " + DEFAULT + "Naper"

#=================
#       Others
#=================
header()
type = 1
fluidsynth.init(loadSf(args.play[0]),"alsa")
if type == 2:
	pygame.mixer.music.play()
	pygame.mixer.music.pause()
	playstat = 0
if args.save:
	""" create new Notecontainer """
	nc = NoteContainer()
while True:
	#pygame.mixer.music.pause()
	screen.fill((white))
	screen.blit(background,(0,0))
	pygame.display.flip()
	if pygame.key.get_focused():
		playstat = 1
	else:
		playstat = 0
	events = pygame.event.get()
	event = pygame.event.poll()
	for event in events:
		note = ""
		note_type = 0
		if type == 1:
示例#11
0
    print YELLOW + "@ author " + DEFAULT + "Naper"


#=================
#       Others
#=================
header()
type = 1
fluidsynth.init(loadSf(args.play[0]), "alsa")
if type == 2:
    pygame.mixer.music.play()
    pygame.mixer.music.pause()
    playstat = 0
if args.save:
    """ create new Notecontainer """
    nc = NoteContainer()
while True:
    #pygame.mixer.music.pause()
    screen.fill((white))
    screen.blit(background, (0, 0))
    pygame.display.flip()
    if pygame.key.get_focused():
        playstat = 1
    else:
        playstat = 0
    events = pygame.event.get()
    event = pygame.event.poll()
    for event in events:
        note = ""
        note_type = 0
        if type == 1:
示例#12
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
示例#13
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
示例#14
0
from mingus.containers import Note
from mingus.containers import NoteContainer
from mingus.containers import Bar
from mingus.containers import Track
from mingus.containers.instrument import Instrument, Piano, Guitar
from mingus.containers import Composition
from mingus.midi.midi_file_out import write_Composition

eb = Note("Eb", 4)
g = Note("G", 4)
bb = Note("Bb", 4)
n = NoteContainer([eb, g, bb])
c = Composition()
c.set_author('Dusty Carver', '*****@*****.**')
c.set_title('Late Nights')
t = Track(Guitar())
b = Bar('Eb', (4, 4))
b.place_notes(n, 4)
b.place_notes(n, 4)
b.place_notes(n, 4)
b.place_notes(None, 4)
t.add_bar(b)
c.add_track(t)

write_Composition("one.mid", c)
示例#15
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"
        key = 'C'
    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"
        key = 'C'
    if num == 3:
        test_scale = scales.Major("C")
        for i in range(7):
            track + test_scale[i]
        key = 'C'
    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)
        key = 'C'

    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)

        key = 'A'

    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)
        key = 'C#'
    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)

        key = 'C'

    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)
        key = 'E'
    return (track, key)