Exemple #1
0
class Piano(Instrument):

    name = 'Piano'
    range = (Note('F', 0), Note('B', 8))

    def __init__(self):
        Instrument.__init__(self)
Exemple #2
0
    def get_Note(
        self,
        string=0,
        fret=0,
        maxfret=24,
        ):
        """Returns the Note on `string`, `fret`. Throws a RangeError if either the \
fret or string is unplayable.
{{{
>>> t = tunings.StringTuning(\"test\", \"test\", ['A-3', 'A-4'])
>>> t,get_Note(0, 0)
'A-3'
>>> t.get_Note(0, 1)
'A#-3'
>>> t.get_Note(1, 0)
'A-4'
}}}"""

        if 0 <= string < self.count_strings():
            if 0 <= fret <= maxfret:
                s = self.tuning[string]
                if type(s) == list:
                    s = s[0]
                n = Note(int(s) + fret)
                n.string = string
                n.fret = fret
                return n
            else:
                raise RangeError("Fret '%d' on string '%d' is out of range"\
                     % (string, fret))
        else:
            raise RangeError("String '%d' out of range" % string)
 def test_sort(self):
     n1 = NoteContainer(['Eb', 'Gb', 'C'])
     n2 = NoteContainer(['Eb', 'Gb', 'Cb'])
     n1.sort()
     n2.sort()
     self.assertEqual(Note('Eb'), n1[0])
     self.assertEqual(Note('Gb'), n2[1])
    def get_Note(
        self,
        string=0,
        fret=0,
        maxfret=24,
        ):
        """Returns the Note on `string`, `fret`. Throws a RangeError if either the \
fret or string is unplayable.
{{{
>>> t = tunings.StringTuning(\"test\", \"test\", ['A-3', 'A-4'])
>>> t,get_Note(0, 0)
'A-3'
>>> t.get_Note(0, 1)
'A#-3'
>>> t.get_Note(1, 0)
'A-4'
}}}"""

        if 0 <= string < self.count_strings():
            if 0 <= fret <= maxfret:
                s = self.tuning[string]
                if type(s) == list:
                    s = s[0]
                n = Note(int(s) + fret)
                n.string = string
                n.fret = fret
                return n
            else:
                raise RangeError, "Fret '%d' on string '%d' is out of range"\
                     % (string, fret)
        else:
            raise RangeError, "String '%d' out of range" % string
Exemple #5
0
def blues_scale(key):
    """Return a blues scale in a given key"""
    major_scale = list(scales.ionian(key))

    #Use mingus.containers.Note to represent notes so we have octave info
    for i, note in enumerate(major_scale):
        major_scale[i] = Note(note)
        if i>0 and major_scale[i]<major_scale[i-1]:
            major_scale[i].octave_up()

    # mingus.Scales is dumb, this is a workaround =/
    fifth = Note(major_scale[4])
    major_scale[2].diminish()
    major_scale[4].diminish()
    major_scale[6].diminish()
    seventh = Note(major_scale[0])
    seventh.octave_up()

    #assemble the blues scale
    blues_scale = [major_scale[0],
                   major_scale[2],
                   major_scale[3],
                   major_scale[4],
                   fifth,
                   major_scale[6],
                   seventh]

    return blues_scale
Exemple #6
0
def main():
    if not os.path.isfile('./data/probs.json'):
        print ('Creating json file...')
        fname = "./data/interval-5gram.csv"
        counts = get_counts(fname, 4)
        probs = get_probs(counts)
        with open('./data/probs.json', 'w') as outfile:
            json.dump(probs, outfile)

    with open('./data/probs.json', 'r') as infile:
        probs_dict = json.load(infile, encoding='utf-8')

    start_int = C4
    melody = []
    fluidsynth.init("/usr/share/sounds/sf2/FluidR3_GM.sf2", "alsa")

    streamer = stream_notes(probs_dict)
    for i in range(100):
        next_int = start_int + int(next(streamer))
        next_note = Note()
        next_note.from_int(next_int)

        melody.append(next_note)
        start_int = next_int
        print(next_note)
        fluidsynth.play_Note(next_note)
        time.sleep(.2)
def generate_pattern(progression_list, key = "C", pattern_index = 0, nb_bars=1):
    pattern = patterns.PATTERNS[pattern_index]
    t = Track()
    for progression in progression_list:
        progression = progression_to_int(progression)
        for p in progression : # permet d'avancer dans la progression des mesures
            previews_note = None
            p_key = get_progression_key(p, key)
            b = Bar(key, (4, 4))
            position_note = 0
            already_used=[]
            for pattern_note in pattern :
                if position_note not in already_used :
                    is_chord = chord_length(pattern_note, pattern, position_note)
                    if is_chord[2] :
                        note_list = []
                        # c est un accord
                        for p_note in pattern[is_chord[0]:is_chord[1]+1] :
                            note_str = get_note_pattern(p_note, p_key)
                            note = Note(note_str, p_note[5])
                            if previews_note is not None:
                                if p_note[4]=='+':
                                    if int(note) < previews_note :
                                        note.octave_up()
                                elif p_note[4]=='-':
                                    if int(note) > previews_note :
                                        note.octave_down()      
                            previews_note = int(note)
                            note_list.append(note)
                            
                        for n in range(is_chord[0], is_chord[1]+1):
                            already_used.append(n)
                        
                        b.place_notes(note_list, pattern_note[1])
    
                                
                    else :    
                        note_str = get_note_pattern(pattern_note, p_key)
                        note = Note(note_str, pattern_note[5])
                        
                        if previews_note is not None:
                            if pattern_note[4]=='+':
                                if int(note) < previews_note :
                                    note.octave_up()
    
                            elif pattern_note[4]=='-':
                                if int(note) > previews_note :
                                    note.octave_down()
                                    
                        previews_note = int(note)
                        b.place_notes(note, pattern_note[1])
                        already_used.append(position_note)
                position_note+=1
                
            t.add_bar(b)

    return t
Exemple #8
0
 def play(self, index):
     if index == 0:
         start_note = choice(self.start_notes)
         start_note.channel = BEASTIE_CHANNEL
         end_note = Note(start_note)
         end_note.transpose(choice(self.intervals))
         self.notes = [start_note, end_note]
         self.hl = start_note
     duration = self.note_placement[index][1]
     thread_NoteContainer(self.notes[index], duration, self.instr)
 def test_get_Note(self):
     self.assert_(self.guitar6.get_Note(0, 0) == Note('E-2'))
     self.assert_(self.guitar6.get_Note(1, 0) == Note('A-2'))
     self.assert_(self.guitar6.get_Note(2, 0) == Note('D-3'))
     self.assert_(self.guitar6.get_Note(3, 0) == Note('G-3'))
     self.assert_(self.guitar6.get_Note(3, 3) == Note('A#-3'))
     self.assertRaises(RangeError, self.guitar6.get_Note, -1, 3)
     self.assertRaises(RangeError, self.guitar6.get_Note, 7, 3)
     self.assertRaises(RangeError, self.guitar6.get_Note, 3, -1)
     self.assertRaises(RangeError, self.guitar6.get_Note, 3, 25)
Exemple #10
0
    def set_range(self, range):
        """Sets the range of the instrument. A range is a tuple of two \
[refMingusContainersNote Notes] or note strings."""

        if type(range[0]) == str:
            range[0] = Note(range[0])
            range[1] = Note(range[1])
        if not hasattr(range[0], 'name'):
            raise UnexpectedObjectError("Unexpected object '%s'. Expecting a mingus.containers.Note object"\
                 % range[0])
        self.range = range
Exemple #11
0
def play_pattern(pattern_index, key):
    pattern = patterns.PATTERNS[pattern_index]
    fluidsynth.init("198_u20_Electric_Grand.SF2") # permet d'initialiser l'instrument

    previews_note = None
    b = Bar(key, (4, 4))
    position_note = 0
    already_used=[]
    for pattern_note in pattern :
        if position_note not in already_used :
            is_chord = chord_length(pattern_note, pattern, position_note)
            if is_chord[2] :
                note_list = []
                # c est un accord
                for p_note in pattern[is_chord[0]:is_chord[1]+1] :
                    note_str = get_note_pattern(p_note, key)
                    note = Note(note_str, p_note[5])
                    if previews_note is not None:
                        if p_note[4]=='+':
                            if int(note) < previews_note :
                                note.octave_up()
                        elif p_note[4]=='-':
                            if int(note) > previews_note :
                                note.octave_down()      
                    previews_note = int(note)
                    note_list.append(note)
                    
                for n in range(is_chord[0], is_chord[1]+1):
                    already_used.append(n)
                
                b.place_notes(note_list, pattern_note[1])

                        
            else :    
                note_str = get_note_pattern(pattern_note, key)
                note = Note(note_str, pattern_note[5])
                
                if previews_note is not None:
                    if pattern_note[4]=='+':
                        if int(note) < previews_note :
                            note.octave_up()

                    elif pattern_note[4]=='-':
                        if int(note) > previews_note :
                            note.octave_down()
                            
                previews_note = int(note)
                b.place_notes(note, pattern_note[1])
                already_used.append(position_note)
        position_note+=1
            
    fluidsynth.play_Bar(b, 1, 60)                      
Exemple #12
0
class Guitar(Instrument):

    name = 'Guitar'
    range = (Note('E', 3), Note('E', 7))
    clef = 'Treble'

    def __init__(self):
        Instrument.__init__(self)

    def can_play_notes(self, notes):
        if len(notes) > 6:
            return False
        return Instrument.can_play_notes(self, notes)
Exemple #13
0
 def on_midi(self, msg):
     if is_note_on(msg):
         self.keys[msg.note % 12].pressed = True
         note = Note().from_int(msg.note)
         note.channel, note.velocity = PLAYER_CHANNEL, msg.velocity
         noteThread = KeyboardThread(note)
         self.events[msg.note] = noteThread.event
         noteThread.start()
     elif is_note_off(msg):
         self.keys[msg.note % 12].pressed = False
         self.events[msg.note].set()
     for watcher in self.watchers:
         watcher.dispatch('on_midi', msg)
Exemple #14
0
def find_notes(freqTable, maxNote=100):
    """Converts the (frequencies, amplitude) list to a (Note, amplitude) list."""

    res = [0] * 129
    n = Note()
    for (freq, ampl) in freqTable:
        if freq > 0 and ampl > 0:
            f = _find_log_index(freq)
            if f < maxNote:
                res[f] += ampl
            else:
                res[128] += ampl
    return [(Note().from_int(x) if x < 128 else None, n) for (x, n) in
            enumerate(res)]
 def test_add_notes(self):
     self.assertEqual(self.n3, self.n1.add_notes(['A', 'C', 'E']))
     self.n1.empty()
     self.assertEqual(self.n3,
                      self.n1.add_notes([['A', 4], ['C', 5], ['E', 5]]))
     self.n1.empty()
     self.assertEqual(self.n2, self.n1.add_notes(Note('A')))
     self.n1.empty()
     self.assertEqual(self.n2, self.n1.add_notes([Note('A')]))
     self.n1.empty()
     self.assertEqual(self.n2, self.n1.add_notes('A'))
     self.n1.empty()
     self.assertEqual(self.n3,
                      self.n2 + NoteContainer([['C', 5], ['E', 5]]))
     self.n2 = NoteContainer('A')
Exemple #16
0
    def find_frets(self, note, maxfret=24):
        """Returns a list with for each string the fret on which the note is played \
or None if it can't be played on that particular string. `maxfret` is \
the highest fret that can be played. `note` should either be a string or \
a Note object.
{{{
>>> t = tunings.StringTuning(\"test\", \"test\", [\"A-3\", \"E-4\"])
>>> t.find_frets(Note(\"C-4\")
[3, None]
>>> t.find_frets(Note(\"A-4\")
[12, 5]
}}}"""

        result = []
        if type(note) == str:
            note = Note(note)
        for x in self.tuning:
            if type(x) == list:
                base = x[0]
            else:
                base = x
            diff = base.measure(note)
            if 0 <= diff <= maxfret:
                result.append(diff)
            else:
                result.append(None)
        return result
Exemple #17
0
def from_Track(track):
    """Processes a [refMingusContainersTrack Track] object and returns the Lilypond \
equivalent in a string."""

    # Throw exception

    if not hasattr(track, 'bars'):
        return False
    lastkey = Note('C')
    lasttime = (4, 4)

    # Handle the Bars:

    result = ''
    for bar in track.bars:
        if lastkey != bar.key:
            showkey = True
        else:
            showkey = False
        if lasttime != bar.meter:
            showtime = True
        else:
            showtime = False
        result += from_Bar(bar, showkey, showtime) + ' '
        lastkey = bar.key
        lasttime = bar.meter
    return '{ %s}' % result
Exemple #18
0
 def test_set_item(self):
     b = Bar()
     b + ['A', 'C', 'E']
     c = Bar()
     c + ['A', 'C', 'E']
     self.assertEqual(b, c)
     c[0] = NoteContainer(['A', 'C', 'E'])
     self.assertEqual(b, c)
     c[0] = ['A', 'C', 'E']
     self.assertEqual(b, c)
     c[0] = Note('A')
     c[0] = c[0][2] + NoteContainer(['C', 'E'])
     self.assertEqual(b, c)
     c[0] = Note('A')
     c[0] = c[0][2] + 'C'
     c[0] = c[0][2] + 'E'
     self.assertEqual(b, c)
Exemple #19
0
    def generate_note(self, state):
        wild = 1.0
        if "wild" in state:
            wild = state["wild"]

        if state["tick"] % (state["resolution"] / 4.0) == 0 and random() < 1.0 * wild:
            n = Note(choice(state["chord"]))
            while n > Note("E", 3):
                if n.octave >= 3:
                    n.octave_down()
                else:
                    break
            return [n]
        elif (
            state["resolution"] > 4
            and state["tick"] % (state["resolution"] / 4.0) == state["resolution"] / 8
            and random() < 0.2 * wild
        ):

            n = Note(choice(state["chord"]))
            while n > Note("E", 3):
                if n.octave >= 3:
                    n.octave_down()
                else:
                    break
            n.name = notes.diminish(n.name)
            return [n]
	def generate_note(self, state):

		if state["tick"] % (state["resolution"] / 2.0) == 0 \
				and random() < 5.0 * state["wild"]:
			if random() > 0.1:
				n = Note(state["chord"][0])
			else:
				if len(state["chord"]) == 1:
					n = Note(state["chord"][0])
				if len(state["chord"]) == 2:
					n = Note(state["chord"][1])
				else:
					n = Note(state["chord"][2])
			n.octave_down()
			return [n]
		
		if state["tick"] % (state["resolution"] / 2.0) == \
				state["resolution"] / 4 \
				and random() < 5.0 *state["wild"]:
			c = state["chord"]

			for i in range(len(state["chord"])):
				if random() < 0.3 * state["wild"]:
					c = chords.invert(c)

			n = NoteContainer(c)

			return n
		return None
Exemple #21
0
	def test_from_hertz(self):
		a = Note()
		a.from_hertz(440)
		self.assertEqual(a, Note("A", 4))
		a.from_hertz(880)
		self.assertEqual(a, Note("A", 5))
		a.from_hertz(1760)
		self.assertEqual(a, Note("A", 6))
Exemple #22
0
def bassline(chord, beat_probas):

    chord_tones = chords.from_shorthand(chord)
    octave = 2

    b = Bar()

    for (bass, els, octa) in beat_probas:
        p = random.random()
        if p < bass:
            b.place_notes(Note(chord_tones[0], octave), 8)
        elif p < bass + els:
            b.place_notes(Note(random.choice(chord_tones[1:]), octave), 8)
        elif p < bass + els + octa:
            b.place_notes(Note(chord_tones[0], octave + 1), 8)
        else:
            b.place_rest(8)

    return b
Exemple #23
0
    def __init__(self, note, octave, duration):
        self.note = str(note)
        self.octave = '' if octave is None else octave
        self.duration = duration
        self.mingus_duration = int(duration)

        if self.note == 'P':
            self.mingus_note = None
        else:
            self.mingus_note = Note(self.note, int(self.octave))
Exemple #24
0
    def note_in_range(self, note):
        """Tests whether note is in the range of this Instrument. Returns `True` if \
so, `False` otherwise"""

        if type(note) == str:
            note = Note(note)
        if not hasattr(note, 'name'):
            raise UnexpectedObjectError("Unexpected object '%s'. Expecting a mingus.containers.Note object"\
                 % note)
        if note >= self.range[0] and note <= self.range[1]:
            return True
        return False
 def test_set_note(self):
     n = Note()
     self.assert_(n.set_note("C", 5, {}))
     n.empty()
     self.assert_(n.set_note("C-5"))
     self.assert_(n.set_note("C", 5))
     self.assert_(n.set_note("C#-12", 5))
     self.assertRaises(NoteFormatError, n.set_note, "H")
     self.assertRaises(NoteFormatError, n.set_note, "C 23")
     self.assertRaises(NoteFormatError, n.set_note, "C# 123")
Exemple #26
0
    def __init__(
        self,
        instrument,
        description,
        tuning,
        ):
        """`instrument` and `description` should be strings. tuning should be a \
list of strings or a list of lists of strings that denote courses. See \
tunings.add_tuning for examples."""

        self.instrument = instrument
        self.tuning = []

                # convert to Note

        for x in tuning:
            if type(x) == list:
                self.tuning.append([Note(n) for n in x])
            else:
                self.tuning.append(Note(x))
        self.description = description
Exemple #27
0
 def test_set_note(self):
     n = Note()
     self.assert_(n.set_note('C', 5, {}))
     n.empty()
     self.assert_(n.set_note('C-5'))
     self.assert_(n.set_note('C', 5))
     self.assert_(n.set_note('C#-12', 5))
     self.assertRaises(NoteFormatError, n.set_note, 'H')
     self.assertRaises(NoteFormatError, n.set_note, 'C 23')
     self.assertRaises(NoteFormatError, n.set_note, 'C# 123')
Exemple #28
0
    def test_tie_together(self):
        n = Note('G')
        m = Note('G')
        m.tie_together(n)
        self.bar1.place_notes('C', 2)
        self.bar1.place_notes('G', 4)
        self.bar1.place_notes(n, 4)
        self.bar2.place_notes(m, 4)
        self.bar2.place_notes('C', 2)

        self.assertEqual(m.tie_note(), n)
        self.assertEqual(n.next_note(), m)
        self.assertTrue(n.is_tied())
        self.assertTrue(m.is_last_tied())
 def test_from_hertz(self):
     a = Note()
     self.assertEqual(a.from_hertz(55.5), Note("A", 1))
     self.assertEqual(a.from_hertz(110), Note("A", 2))
     a.from_hertz(220)
     self.assertEqual(a, Note("A", 3))
     a.from_hertz(440)
     self.assertEqual(a, Note("A", 4))
     a.from_hertz(880)
     self.assertEqual(a, Note("A", 5))
     a.from_hertz(1760)
     self.assertEqual(a, Note("A", 6))
def generate_pattern(progression_list, key = "C", pattern = ((1, 4, 1, "none", '=', 3), (3, 4, 2,"none", '+', 3), (5, 4, 3, "none", '+', 3), (6, 4, 4, "none", '+', 3)), nb_bars=1):
    #pattern = ((1, 4, 1, "none", '=', 3), (5, 4, 1, "none", '+', 3), (1, 4, 2, "none", '+', 3), (6, 4, 2, "none", '+', 3), (1, 4, 3, "none", '=', 3), (5, 4, 3, "none", '+', 3), (1, 4, 4, "none", '+', 3), (6, 4, 4, "none", '+', 3))
    #pattern = ((1, 8, 1, "none", '=', 2), (5, 8, 1, "none", '+', 2), (1, 8, 1.5, "none", '=', 2), (5, 8, 1.5, "none", '+', 2), (2, 8, 2, "diese", '=', 2), (3, 8, 2.5, "none", '+', 2), (1, 8, 3, "none", '=', 2), (5, 8, 3, "none", '+', 2), (1, 8, 3.5, "none", '=', 2), (5, 8, 3.5, "none", '+', 2), (2, 8, 4, "diese", '=', 2), (3, 8, 4.5, "none", '+', 2))
    #pattern = ((1, 8, 1, "none", '=', 3), (5, 8, 1, "none", '+', 3), (1, 8, 1.5, "none", '=', 3), (5, 8, 1.5, "none", '+', 3), (2, 8, 2, "diese", '-', 3), (3, 8, 2.5, "none", '+', 3), (1, 8, 3, "none", '=', 3), (5, 8, 3, "none", '+', 3), (1, 8, 3.5, "none", '=', 3), (5, 8, 3.5, "none", '+', 3), (1, 8, 4, "none", '=', 3), (6, 8, 4, "none", '+', 3), (1, 8, 4.5, "none", '=', 3), (6, 8, 4.5, "none", '+', 3))
    t = Track()
    for progression in progression_list:
        progression = progression_to_int(progression)
        for p in progression : # permet d'avancer dans la progression des mesures
            previews_note = None
            p_key = get_progression_key(p, key)
            b = Bar(key, (4, 4))
            position_note = 0
            already_used=[]
            for pattern_note in pattern :
                if position_note not in already_used :
                    is_chord = chord_length(pattern_note, pattern, position_note)
                    if is_chord[2] :
                        note_list = []
                        # c est un accord
                        for p_note in pattern[is_chord[0]:is_chord[1]+1] :
                            note_str = get_note_pattern(p_note, p_key)
                            note = Note(note_str, p_note[5])
                            if previews_note is not None:
                                if p_note[4]=='+':
                                    if int(note) < previews_note :
                                        note.octave_up()
                                elif p_note[4]=='-':
                                    if int(note) > previews_note :
                                        note.octave_down()      
                            previews_note = int(note)
                            note_list.append(note)
                            
                        for n in range(is_chord[0], is_chord[1]+1):
                            already_used.append(n)
                        
                        b.place_notes(note_list, pattern_note[1])
    
                                
                    else :    
                        note_str = get_note_pattern(pattern_note, p_key)
                        note = Note(note_str, pattern_note[5])
                        
                        if previews_note is not None:
                            if pattern_note[4]=='+':
                                if int(note) < previews_note :
                                    note.octave_up()
    
                            elif pattern_note[4]=='-':
                                if int(note) > previews_note :
                                    note.octave_down()
                                    
                        previews_note = int(note)
                        b.place_notes(note, pattern_note[1])
                        already_used.append(position_note)
                position_note+=1
                
            t.add_bar(b)
    print(str(t))
                    
    #track = LilyPond.from_Track(t)
    #test = LilyPond.to_png(track, "left_hand")
    #MidiFileOut.write_Track("test_midi.mid", t)
    return t
Exemple #31
0
from mingus.containers.Note import Note
from mingus.containers.Bar import Bar

from random import random

BASS = Note('C', 2)
SNARE = Note('E', 2)
HIHAT = Note('C#', 2)


def drum_beat(beat_probas):
    b = Bar()

    for (bass, snare, hhat) in beat_probas:
        p = random()
        if p < bass:
            b.place_notes(BASS, 8)
        elif p < bass + snare:
            b.place_notes(SNARE, 8)
        elif p < bass + snare + hhat:
            b.place_notes(HIHAT, 8)
        else:
            b.place_rest(8)

    return b
def get_note_between(previous_note, next_note, liste_note):
    selected_notes= []
    if previous_note < next_note:
        if int(next_note)-int(previous_note)<3:
            min = Note(previous_note)
            max = Note(next_note)
            for i in range(2):
                min.diminish()    
                max.augment()
        else:
            min = Note(previous_note)
            max = Note(next_note)
    elif previous_note > next_note:
        if int(previous_note)-int(next_note)<3:
            min = Note(next_note)
            max = Note(previous_note)
            for i in range(2):
                min.diminish()    
                max.augment()
        else:
            min = Note(next_note)
            max = Note(previous_note)
    elif previous_note == next_note:
        min = Note(next_note)
        max = Note(previous_note)
        for i in range(4):
            min.diminish()    
            max.augment()
    
    for i in range(len(liste_note)):
        current = Note(liste_note[i])
        if current not in selected_notes:
            if min<=current and current<=max:
                selected_notes.append(current)
    return selected_notes
Exemple #33
0
class Key(avg.RectNode):
	def __init__(self, size, pos, pitch, isWhite, parent=None, **kwargs):
		super(Key, self).__init__(**kwargs)
		if parent:
			parent.appendChild(self)
		self.size = size
		self.pos = pos
		self.pitch = pitch
		self.isWhite = isWhite
		self.fillopacity = 1
		self.setNote()
		
		if self.isWhite:
			self.fillcolor = "FFFFFF"
			self.color = "000000"
			self.onDown = self.onWhiteDown
			self.onUp = self.onWhiteUp
			self.onOut = self.onWhiteOut
		else:
			self.fillcolor = "000000"
			self.color = "000000"
			self.onDown = self.onBlackDown
			self.onUp = self.onBlackUp
			self.onOut = self.onBlackOut
		
		self.setEventHandler(avg.CURSORDOWN, avg.MOUSE | avg.TOUCH, self.onDown)
		self.setEventHandler(avg.CURSORUP, avg.MOUSE | avg.TOUCH, self.onUp)
		self.setEventHandler(avg.CURSOROUT, avg.MOUSE | avg.TOUCH, self.onOut)
	
	def setNote(self):
		self.note = Note()
		self.note.from_int(self.pitch-12)
	
	def onDown(self, event):
		pass
	
	def onUp(self, event):
		pass
	
	def onOut(self, event):
		pass
	
	def onWhiteDown(self, event):
		self.fillcolor = "C0C0C0"
		fluidsynth.play_Note(self.note)
	
	def onWhiteUp(self, event):
		self.fillcolor = "FFFFFF"
		
	
	def onWhiteOut(self, event):
		self.fillcolor = "FFFFFF"
		
	
	def onBlackDown(self, event):
		self.fillcolor = "C0C0C0"
		fluidsynth.play_Note(self.note)
	
	def onBlackUp(self, event):
		self.fillcolor = "000000"
	
	def onBlackOut(self, event):
		self.fillcolor = "000000"
Exemple #34
0
 def different_channel():
     n = Note('G')
     m = Note('G', dynamics={'channel': n.channel+1})
     m.tie_together(n)
 def test_getitem(self):
     self.assertEqual(self.n2[0], Note('A'))
     self.assertEqual(self.n3[0], Note('A'))
     self.assertEqual(self.n4[0], Note('A'))
     self.assertEqual(self.n4[1], Note('C', 5))
     self.assertEqual(self.n4[2], Note('E', 5))
Exemple #36
0
class Instrument:
    """The Instrument class is pretty self explanatory. Instruments can be used \
with [refMingusContainersTrack Tracks] to define which instrument plays \
what, with the added bonus of checking whether the entered notes are in the \
range of the instrument.

It's probably easiest to subclass your own Instruments (see \
[refMingusContainersPiano Piano] and [refMingusContainersGuitar Guitar] for \
examples)."""

    name = 'Instrument'
    range = (Note('C', 0), Note('C', 8))
    clef = 'bass and treble'
    tuning = None  # optional StringTuning object

    def __init__(self):
        pass

    def set_range(self, range):
        """Sets the range of the instrument. A range is a tuple of two \
[refMingusContainersNote Notes] or note strings."""

        if type(range[0]) == str:
            range[0] = Note(range[0])
            range[1] = Note(range[1])
        if not hasattr(range[0], 'name'):
            raise UnexpectedObjectError, \
                "Unexpected object '%s'. Expecting a mingus.containers.Note object"\
                 % range[0]
        self.range = range

    def note_in_range(self, note):
        """Tests whether note is in the range of this Instrument. Returns `True` if \
so, `False` otherwise"""

        if type(note) == str:
            note = Note(note)
        if not hasattr(note, 'name'):
            raise UnexpectedObjectError, \
                "Unexpected object '%s'. Expecting a mingus.containers.Note object"\
                 % note
        if note >= self.range[0] and note <= self.range[1]:
            return True
        return False

    def notes_in_range(self, notes):
        """An alias for can_play_notes"""

        return can_play_notes(notes)

    def can_play_notes(self, notes):
        """Will test if the notes lie within the range of the instrument. Returns \
`True` if so, `False` otherwise."""

        if hasattr(notes, 'notes'):
            notes = notes.notes
        if type(notes) != list:
            notes = [notes]
        for n in notes:
            if not self.note_in_range(n):
                return False
        return True

    def __repr__(self):
        """A string representation of the object"""

        return '%s [%s - %s]' % (self.name, self.range[0], self.range[1])
Exemple #37
0
class MidiInstrument(Instrument):

    range = (Note('C', 0), Note('B', 8))
    instrument_nr = 1
    name = ''
    names = [
        'Acoustic Grand Piano',
        'Bright Acoustic Piano',
        'Electric Grand Piano',
        'Honky-tonk Piano',
        'Electric Piano 1',
        'Electric Piano 2',
        'Harpsichord',
        'Clavi',
        'Celesta',
        'Glockenspiel',
        'Music Box',
        'Vibraphone',
        'Marimba',
        'Xylophone',
        'Tubular Bells',
        'Dulcimer',
        'Drawbar Organ',
        'Percussive Organ',
        'Rock Organ',
        'Church Organ',
        'Reed Organ',
        'Accordion',
        'Harmonica',
        'Tango Accordion',
        'Acoustic Guitar (nylon)',
        'Acoustic Guitar (steel)',
        'Electric Guitar (jazz)',
        'Electric Guitar (clean)',
        'Electric Guitar (muted)',
        'Overdriven Guitar',
        'Distortion Guitar',
        'Guitar harmonics',
        'Acoustic Bass',
        'Electric Bass (finger)',
        'Electric Bass (pick)',
        'Fretless Bass',
        'Slap Bass 1',
        'Slap Bass 2',
        'Synth Bass 1',
        'Synth Bass 2',
        'Violin',
        'Viola',
        'Cello',
        'Contrabass',
        'Tremolo Strings',
        'Pizzicato Strings',
        'Orchestral Harp',
        'Timpani',
        'String Ensemble 1',
        'String Ensemble 2',
        'SynthStrings 1',
        'SynthStrings 2',
        'Choir Aahs',
        'Voice Oohs',
        'Synth Voice',
        'Orchestra Hit',
        'Trumpet',
        'Trombone',
        'Tuba',
        'Muted Trumpet',
        'French Horn',
        'Brass Section',
        'SynthBrass 1',
        'SynthBrass 2',
        'Soprano Sax',
        'Alto Sax',
        'Tenor Sax',
        'Baritone Sax',
        'Oboe',
        'English Horn',
        'Bassoon',
        'Clarinet',
        'Piccolo',
        'Flute',
        'Recorder',
        'Pan Flute',
        'Blown Bottle',
        'Shakuhachi',
        'Whistle',
        'Ocarina',
        'Lead1 (square)',
        'Lead2 (sawtooth)',
        'Lead3 (calliope)',
        'Lead4 (chiff)',
        'Lead5 (charang)',
        'Lead6 (voice)',
        'Lead7 (fifths)',
        'Lead8 (bass + lead)',
        'Pad1 (new age)',
        'Pad2 (warm)',
        'Pad3 (polysynth)',
        'Pad4 (choir)',
        'Pad5 (bowed)',
        'Pad6 (metallic)',
        'Pad7 (halo)',
        'Pad8 (sweep)',
        'FX1 (rain)',
        'FX2 (soundtrack)',
        'FX 3 (crystal)',
        'FX 4 (atmosphere)',
        'FX 5 (brightness)',
        'FX 6 (goblins)',
        'FX 7 (echoes)',
        'FX 8 (sci-fi)',
        'Sitar',
        'Banjo',
        'Shamisen',
        'Koto',
        'Kalimba',
        'Bag pipe',
        'Fiddle',
        'Shanai',
        'Tinkle Bell',
        'Agogo',
        'Steel Drums',
        'Woodblock',
        'Taiko Drum',
        'Melodic Tom',
        'Synth Drum',
        'Reverse Cymbal',
        'Guitar Fret Noise',
        'Breath Noise',
        'Seashore',
        'Bird Tweet',
        'Telephone Ring',
        'Helicopter',
        'Applause',
        'Gunshot',
    ]

    def __init__(self, name=''):
        self.name = name
 def test_from_Note(self):
     self.assertEqual(LilyPond.from_Note(Note('C'), standalone=False), "c'")
     self.assertEqual(LilyPond.from_Note(Note('C#'), standalone=False),
                      "cis'")
     self.assertEqual(LilyPond.from_Note(Note('C##'), standalone=False),
                      "cisis'")
     self.assertEqual(LilyPond.from_Note(Note('Cb'), standalone=False),
                      "ces'")
     self.assertEqual(LilyPond.from_Note(Note('Cbb'), standalone=False),
                      "ceses'")
     self.assertEqual(LilyPond.from_Note(Note('C', 0), standalone=False),
                      'c,,,')
     self.assertEqual(LilyPond.from_Note(Note('C', 1), standalone=False),
                      'c,,')
     self.assertEqual(LilyPond.from_Note(Note('C', 2), standalone=False),
                      'c,')
     self.assertEqual(LilyPond.from_Note(Note('C', 3), standalone=False),
                      'c')
     self.assertEqual(LilyPond.from_Note(Note('C', 4), standalone=False),
                      "c'")
     self.assertEqual(LilyPond.from_Note(Note('C', 5), standalone=False),
                      "c''")
     self.assertEqual(LilyPond.from_Note(Note('C', 6), standalone=False),
                      "c'''")
     self.assertEqual(LilyPond.from_Note(Note('C', 7), standalone=False),
                      "c''''")
Exemple #39
0
def _drumNote_from_int(i):
    n = Note().from_int(i)
    n.channel = DRUM_TRACK
    return n
Exemple #40
0
 def test_key(self):
     self.assertEqual(self.b.key, Note('C'))
     self.assertEqual(self.c.key, Note('E'))
Exemple #41
0
 def different_note():
     n = Note('G')
     m = Note('C')
     m.tie_together(n)
Exemple #42
0
 def test_transpose(self):
     a = Note('C')
     a.transpose('3')
     self.assertEqual(Note('E'), a)
     a.transpose('b2')
     self.assertEqual(Note('F'), a)
     a.transpose('5')
     self.assertEqual(Note('C', 5), a)
     a.transpose('5', False)
     self.assertEqual(Note('F'), a)
     a = Note('G-5')
     a.transpose('5')
     self.assertEqual(Note('D-6'), a)
     a.transpose('5', False)
     self.assertEqual(Note('G-5'), a)
     a.transpose('5', False)
     self.assertEqual(Note('C-5'), a)
Exemple #43
0
 def test_place_notes_types(self):
     self.assertEqual(True, self.meterless + NoteContainer(['A', 'C']))
     self.assertEqual(True, self.meterless + 'A')
     self.assertEqual(True, self.meterless + Note('A'))
     self.assertEqual(True, self.meterless + ['A', 'B'])
     self.assertEqual(True, self.meterless + [Note('A'), Note('B')])
 def generate_discord_container(self, number):
     return NoteContainer(Note(number))
Exemple #45
0
	def setNote(self):
		self.note = Note()
		self.note.from_int(self.pitch-12)
 def generate_base_container(self, key):
     return NoteContainer(Note(scales.diatonic(key)[0], 2))
Exemple #47
0
	def test_transpose(self):
		a = Note("C")
		a.transpose("3")
		self.assertEqual(Note("E"), a)
		a.transpose("b2")
		self.assertEqual(Note("F"), a)
		a.transpose("5")
		self.assertEqual(Note("C", 5), a)
		a.transpose("5", False)
		self.assertEqual(Note("F"), a)

		a = Note("G-5")
		a.transpose("5")
		self.assertEqual(Note("D-6"), a)
		a.transpose("5", False)
		self.assertEqual(Note("G-5"), a)
		a.transpose("5", False)
		self.assertEqual(Note("C-5"), a)
Exemple #48
0
import struct
import numpy
from mingus.containers.Note import Note
from numpy.fft import fft as _fft
import operator

# Making a frequency-amplitude table   Adapted some ideas and source from:
# http://xoomer.virgilio.it/sam_psy/psych/sound_proc/sound_proc_python.html
#
# The log function turns out to be really, really slow, which adds up quickly.
# So before we do any performance critical calculations we set up a cache of all
# the frequencies we need to look up.

_log_cache = []
for x in xrange(129):
    _log_cache.append(Note().from_int(x).to_hertz())
_last_asked = None


def _find_log_index(f):
    """This function looks up the index of the frequency f in the frequency table. \
Because we are dealing with ranges, this returns the nearest index."""

    global _last_asked, _log_cache
    (begin, end) = (0, 128)

    # Most calls are sequential, this keeps track of the last value asked for so
    # that we need to search much, much less.

    if _last_asked is not None:
        (lastn, lastval) = _last_asked
Exemple #49
0
 def press_key(self, note):
     if self.is_sound_on:
         fluidsynth.play_Note(Note(note))
def main():
  global notes
  global song_pop
  genome = NEAT.Genome(0,2,0,7,False, NEAT.ActivationFunction.UNSIGNED_SIGMOID, NEAT.ActivationFunction.UNSIGNED_SIGMOID, 0, params)
  pop = NEAT.Population(genome, params, True, 1.0) 
  numb = 9
  while(numb<97):
    c = Note()
    notes.append(c.from_int(numb))
    numb = numb+1 
  print notes
  programrun = 1
  genome_list = NEAT.GetGenomeList(pop)
  for genomes in genome_list:
    gen_Song(genomes)
  while(programrun == 1):
    choice = raw_input("Choose one of the following\n1) Print population\n2) Eval population using fitness func\n3) Manually set fitness\n4) Print pop Fitness\n5) Play pop member\n6) Pop epoch\n7) Print leaders\n8) Quit\n")
    if(choice == "1"): #Print population
      print_pop()

    elif(choice == "2"): #Evaluate using fitness
      choice = raw_input("How many generations would you like to run?\n")
      for y in range(0, int(choice)-1):
        x = 0
        for genomes in genome_list:
          genomes.SetFitness(evaluate(song_pop[x]))
          x=x+1
        leader = get_leader(genome_list)
        leader_list.append(leader)
        pop.Epoch()
        song_pop = []
        genome_list = NEAT.GetGenomeList(pop)
        for genomes in genome_list:
          gen_Song(genomes)
      x = 0
      for genomes in genome_list:
        genomes.SetFitness(evaluate(song_pop[x]))
        x = x+1
      leader_list.append(get_leader(genome_list))
    
    elif(choice == "3"):
      song_select = raw_input("What member's fitness do you want to set?\n")
      new_fit = raw_input("Enter desired fitness\n")
      old_fit = genome_list[int(song_select) - 1].GetFitness()
      genome_list[int(song_select)-1].SetFitness(float(new_fit))
      print "Member", song_select,"fitness changed from", old_fit, "to", new_fit,"\n"
      
    elif(choice == "4"): #print fitness of pop
      x = 1
      for genomes in genome_list:
        print "Song", x, "has fitness of", genomes.GetFitness(), "\n"
        x =  x+1

    elif(choice == "5"): #Play pop member
      choice = raw_input("What member would you like to play?\n")
      play_song(song_pop[int(choice)-1])

    elif(choice == "6"): #Pop epoch
      pop.Epoch()
      song_pop = []
      genome_list = NEAT.GetGenomeList(pop)
      for genomes in genome_list:
        gen_Song(genomes)
     
    elif(choice == "7"):
      x = 1
      for leader in leader_list:
        print "Member", leader[0]+1, "in gen", x, "has fitness of", leader[2]
        x = x + 1
        

    elif(choice == "8"): #Exit program
      sys.exit("Program exited")

    else:
      print "Not a valid choice, choose again.\n"
def testTaSequencer():
   import sf2
   m = taSequencer("ChoriumRevA.SF2")
   m.play_Note(Note("C-5"))
Exemple #52
0
 def test_get_range(self):
     self.b + NoteContainer(['C', 'E'])
     self.assertEqual((Note('C'), Note('E')), self.b.get_range())
def generate_bar(previews_note, bar, key, mode, progression, progression_list, nb_p, pattern_index):
    if mode == 'mixolydien' :
        if progression == 'IV' :
            key = intervals.fourth(key, key)
        elif progression == 'V' :
            key = intervals.fifth(key, key)
        
    b = Bar(key, (4, 4))
    position_note = 0
    already_used=[]
    list_note = []
    
    for bar_note in bar :
        if position_note not in already_used :
            is_chord = chord_length(bar_note, bar, position_note)
            if is_chord[2] :
                note_list = []
                # c est un accord
                for p_note in bar[is_chord[0]:is_chord[1]+1] :
                    note_str = get_note(p_note, key)
                    note = Note(note_str, p_note[5])
                    if previews_note is not None:
                        if p_note[4]=='+':
                            if int(note) < previews_note :
                                note.octave_up()
                        elif p_note[4]=='-':
                            if int(note) > previews_note :
                                note.octave_down()
                    current_progression = progression_list[0][nb_p]
                    note = change_note_if_needed(bar_note[2], note, pattern_index, current_progression, bar_note, key)     
                    previews_note = int(note)
                    
                    #appeler best_note la aussi
                    note_list.append(note)
                    list_note.append(note)
                    
                for n in range(is_chord[0], is_chord[1]+1):
                    already_used.append(n)
                
                b.place_notes(note_list, bar_note[1])

                        
            else :  
                note_str = get_note(bar_note, key)
                note = Note(note_str, bar_note[5])
                
                if previews_note is not None:
                    if bar_note[4]=='+':
                        if int(note) < previews_note :
                            note.octave_up()

                    elif bar_note[4]=='-':
                        if int(note) > previews_note :
                            note.octave_down()
                
                # la un faut appeler le truc pour modifier la note
                current_progression = progression_list[0][nb_p]
                note = change_note_if_needed(bar_note[2], note, pattern_index, current_progression, bar_note, key)
                            
                previews_note = int(note)
                list_note.append(note)
                b.place_notes(note, bar_note[1])
                already_used.append(position_note)
        position_note+=1
     
    return (b, previews_note, list_note)
Exemple #54
0
 def note_off(self, channel, pitch, velocity=100):
     note = Note()
     note.from_int(pitch)
     note.velocity = velocity
     fluidsynth.stop_Note(note, channel)