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])
Beispiel #2
0
class Piano(Instrument):

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

    def __init__(self):
        Instrument.__init__(self)
 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)
Beispiel #4
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
Beispiel #5
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)
Beispiel #6
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')
Beispiel #8
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
Beispiel #9
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
Beispiel #10
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)
Beispiel #11
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)
Beispiel #12
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))
Beispiel #13
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
Beispiel #14
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
Beispiel #15
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
Beispiel #16
0
 def press_key(self, note):
     if self.is_sound_on:
         fluidsynth.play_Note(Note(note))
Beispiel #17
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 generate_base_container(self, key):
     return NoteContainer(Note(scales.diatonic(key)[0], 2))
 def generate_discord_container(self, number):
     return NoteContainer(Note(number))
Beispiel #20
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])
Beispiel #21
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''''")
Beispiel #23
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
Beispiel #24
0
 def test_key(self):
     self.assertEqual(self.b.key, Note('C'))
     self.assertEqual(self.c.key, Note('E'))
Beispiel #25
0
 def test_get_range(self):
     self.b + NoteContainer(['C', 'E'])
     self.assertEqual((Note('C'), Note('E')), self.b.get_range())
Beispiel #26
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 testTaSequencer():
   import sf2
   m = taSequencer("ChoriumRevA.SF2")
   m.play_Note(Note("C-5"))
 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))