Search is not available for this dataset
text
stringlengths
75
104k
def int_to_note(note_int, accidentals='#'): """Convert integers in the range of 0-11 to notes in the form of C or C# or Db. Throw a RangeError exception if the note_int is not in the range 0-11. If not specified, sharps will be used. Examples: >>> int_to_note(0) 'C' >>> int_to_note(3)...
def is_valid_note(note): """Return True if note is in a recognised format. False if not.""" if not _note_dict.has_key(note[0]): return False for post in note[1:]: if post != 'b' and post != '#': return False return True
def note_to_int(note): """Convert notes in the form of C, C#, Cb, C##, etc. to an integer in the range of 0-11. Throw a NoteFormatError exception if the note format is not recognised. """ if is_valid_note(note): val = _note_dict[note[0]] else: raise NoteFormatError("Unknown note...
def reduce_accidentals(note): """Reduce any extra accidentals to proper notes. Example: >>> reduce_accidentals('C####') 'E' """ val = note_to_int(note[0]) for token in note[1:]: if token == 'b': val -= 1 elif token == '#': val += 1 else: ...
def remove_redundant_accidentals(note): """Remove redundant sharps and flats from the given note. Examples: >>> remove_redundant_accidentals('C##b') 'C#' >>> remove_redundant_accidentals('Eb##b') 'E' """ val = 0 for token in note[1:]: if token == 'b': val -= 1 ...
def _gcd(a=None, b=None, terms=None): """Return greatest common divisor using Euclid's Algorithm.""" if terms: return reduce(lambda a, b: _gcd(a, b), terms) else: while b: (a, b) = (b, a % b) return a
def write_Composition(composition, filename, zip=False): """Create an XML file (or MXL if compressed) for a given composition.""" text = from_Composition(composition) if not zip: f = open(filename + '.xml', 'w') f.write(text) f.close() else: import zipfile import ...
def get_key_signature(key='C'): """Return the key signature. 0 for C or a, negative numbers for flat key signatures, positive numbers for sharp key signatures. """ if not is_valid_key(key): raise NoteFormatError("unrecognized format for key '%s'" % key) for couple in keys: if k...
def get_key_signature_accidentals(key='C'): """Return the list of accidentals present into the key signature.""" accidentals = get_key_signature(key) res = [] if accidentals < 0: for i in range(-accidentals): res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b')) elif...
def get_notes(key='C'): """Return an ordered list of the notes in this natural key. Examples: >>> get_notes('F') ['F', 'G', 'A', 'Bb', 'C', 'D', 'E'] >>> get_notes('c') ['C', 'D', 'Eb', 'F', 'G', 'Ab', 'Bb'] """ if _key_cache.has_key(key): return _key_cache[key] if not is_va...
def attach(self, listener): """Attach an object that should be notified of events. The object should have a notify(msg_type, param_dict) function. """ if listener not in self.listeners: self.listeners.append(listener)
def detach(self, listener): """Detach a listening object so that it won't receive any events anymore.""" if listener in self.listeners: self.listeners.remove(listener)
def notify_listeners(self, msg_type, params): """Send a message to all the observers.""" for c in self.listeners: c.notify(msg_type, params)
def set_instrument(self, channel, instr, bank=0): """Set the channel to the instrument _instr_.""" self.instr_event(channel, instr, bank) self.notify_listeners(self.MSG_INSTR, {'channel': int(channel), 'instr': int(instr), 'bank': int(bank)})
def control_change(self, channel, control, value): """Send a control change message. See the MIDI specification for more information. """ if control < 0 or control > 128: return False if value < 0 or value > 128: return False self.cc_event(channel...
def play_Note(self, note, channel=1, velocity=100): """Play a Note object on a channel with a velocity[0-127]. You can either specify the velocity and channel here as arguments or you can set the Note.velocity and Note.channel attributes, which will take presedence over the function arg...
def stop_Note(self, note, channel=1): """Stop a note on a channel. If Note.channel is set, it will take presedence over the channel argument given here. """ if hasattr(note, 'channel'): channel = note.channel self.stop_event(int(note) + 12, int(channel)) ...
def stop_everything(self): """Stop all the notes on all channels.""" for x in range(118): for c in range(16): self.stop_Note(x, c)
def play_NoteContainer(self, nc, channel=1, velocity=100): """Play the Notes in the NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel, 'velocity': velocity}) if nc is None: return True for note in nc: if not ...
def stop_NoteContainer(self, nc, channel=1): """Stop playing the notes in NoteContainer nc.""" self.notify_listeners(self.MSG_PLAY_NC, {'notes': nc, 'channel': channel}) if nc is None: return True for note in nc: if not self.stop_Note(note, channel): ...
def play_Bar(self, bar, channel=1, bpm=120): """Play a Bar object. Return a dictionary with the bpm lemma set on success, an empty dict on some kind of failure. The tempo can be changed by setting the bpm attribute on a NoteContainer. """ self.notify_listeners(s...
def play_Bars(self, bars, channels, bpm=120): """Play several bars (a list of Bar objects) at the same time. A list of channels should also be provided. The tempo can be changed by providing one or more of the NoteContainers with a bpm argument. """ self.notify_listeners(self.MS...
def play_Track(self, track, channel=1, bpm=120): """Play a Track object.""" self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel' : channel, 'bpm': bpm}) for bar in track: res = self.play_Bar(bar, channel, bpm) if res != {}: ...
def play_Tracks(self, tracks, channels, bpm=120): """Play a list of Tracks. If an instance of MidiInstrument is used then the instrument will be set automatically. """ self.notify_listeners(self.MSG_PLAY_TRACKS, {'tracks': tracks, 'channels': channels, 'bpm': bpm}) ...
def play_Composition(self, composition, channels=None, bpm=120): """Play a Composition object.""" self.notify_listeners(self.MSG_PLAY_COMPOSITION, {'composition' : composition, 'channels': channels, 'bpm': bpm}) if channels == None: channels = map(lambda...
def _find_log_index(f): """Look up the index of the frequency f in the frequency table. Return 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...
def find_frequencies(data, freq=44100, bits=16): """Convert audio data into a frequency-amplitude table using fast fourier transformation. Return a list of tuples (frequency, amplitude). Data should only contain one channel of audio. """ # Fast fourier transform n = len(data) p = _fft(...
def find_notes(freqTable, maxNote=100): """Convert 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] += amp...
def data_from_file(file): """Return (first channel data, sample frequency, sample width) from a .wav file.""" fp = wave.open(file, 'r') data = fp.readframes(fp.getnframes()) channels = fp.getnchannels() freq = fp.getframerate() bits = fp.getsampwidth() # Unpack bytes -- warning currentl...
def find_Note(data, freq, bits): """Get the frequencies, feed them to find_notes and the return the Note with the highest amplitude.""" data = find_frequencies(data, freq, bits) return sorted(find_notes(data), key=operator.itemgetter(1))[-1][0]
def analyze_chunks(data, freq, bits, chunksize=512): """Cut the one channel data in chunks and analyzes them separately. Making the chunksize a power of two works fastest. """ res = [] while data != []: f = find_frequencies(data[:chunksize], freq, bits) res.append(sorted(find_notes(...
def find_melody(file='440_480_clean.wav', chunksize=512): """Cut the sample into chunks and analyze each chunk. Return a list [(Note, chunks)] where chunks is the number of chunks where that note is the most dominant. If two consequent chunks turn out to return the same Note they are grouped toget...
def write_Note(file, note, bpm=120, repeat=0, verbose=False): """Expect a Note object from mingus.containers and save it into a MIDI file, specified in file. You can set the velocity and channel in Note.velocity and Note.channel. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] whil...
def write_NoteContainer(file, notecontainer, bpm=120, repeat=0, verbose=False): """Write a mingus.NoteContainer to a MIDI file.""" m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.set_deltatime('\x00') t.play_NoteContainer(notecontainer) t.set_deltatime("...
def write_Bar(file, bar, bpm=120, repeat=0, verbose=False): """Write a mingus.Bar to a MIDI file. Both the key and the meter are written to the file as well. """ m = MidiFile() t = MidiTrack(bpm) m.tracks = [t] while repeat >= 0: t.play_Bar(bar) repeat -= 1 return m.writ...
def write_Track(file, track, bpm=120, repeat=0, verbose=False): """Write a mingus.Track to a MIDI file. Write the name to the file and set the instrument if the instrument has the attribute instrument_nr, which represents the MIDI instrument number. The class MidiInstrument in mingus.containers.Instrum...
def write_Composition(file, composition, bpm=120, repeat=0, verbose=False): """Write a mingus.Composition to a MIDI file.""" m = MidiFile() t = [] for x in range(len(composition.tracks)): t += [MidiTrack(bpm)] m.tracks = t while repeat >= 0: for i in range(len(composition.tracks)...
def get_midi_data(self): """Collect and return the raw, binary MIDI data from the tracks.""" tracks = [t.get_midi_data() for t in self.tracks if t.track_data != ''] return self.header() + ''.join(tracks)
def header(self): """Return a header for type 1 MIDI file.""" tracks = a2b_hex('%04x' % len([t for t in self.tracks if t.track_data != ''])) return 'MThd\x00\x00\x00\x06\x00\x01' + tracks + self.time_division
def write_file(self, file, verbose=False): """Collect the data from get_midi_data and write to file.""" dat = self.get_midi_data() try: f = open(file, 'wb') except: print "Couldn't open '%s' for writing." % file return False try: f....
def fingers_needed(fingering): """Return the number of fingers needed to play the given fingering.""" split = False # True if an open string must be played, thereby making any # subsequent strings impossible to bar with the index finger indexfinger = False # True if the index finger was al...
def add_tuning(instrument, description, tuning): """Add a new tuning to the index. The instrument and description parameters should be strings; tuning should be a list of strings or a list of lists to denote courses. Example: >>> std_strings = ['E-2', 'A-2', 'D-3', 'G-3', 'B-3', 'E-4'] >>> tun...
def get_tuning(instrument, description, nr_of_strings=None, nr_of_courses=None): """Get the first tuning that satisfies the constraints. The instrument and description arguments are treated like case-insensitive prefixes. So search for 'bass' is the same is 'Bass Guitar'. Example: >>> tunings....
def get_tunings(instrument=None, nr_of_strings=None, nr_of_courses=None): """Search tunings on instrument, strings, courses or a combination. The instrument is actually treated like a case-insensitive prefix. So asking for 'bass' yields the same tunings as 'Bass Guitar'; the string 'ba' yields all the ...
def count_courses(self): """Return the average number of courses per string.""" c = 0 for x in self.tuning: if type(x) == list: c += len(x) else: c += 1 return float(c) / len(self.tuning)
def find_frets(self, note, maxfret=24): """Return 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. The maxfret parameter is the highest fret that can be played; note should either be a string or a Note object. ...
def find_fingering(self, notes, max_distance=4, not_strings=[]): """Return a list [(string, fret)] of possible fingerings for 'notes'. The notes parameter should be a list of strings or Notes or a NoteContainer; max_distance denotes the maximum distance between frets; not_string...
def find_chord_fingering(self, notes, max_distance=4, maxfret=18, max_fingers=4, return_best_as_NoteContainer=False): """Return a list of fret lists that are considered possible fingerings. This function only looks at and matches on the note _names_ so it does more than find_fingeri...
def frets_to_NoteContainer(self, fingering): """Convert a list such as returned by find_fret to a NoteContainer.""" res = [] for (string, fret) in enumerate(fingering): if fret is not None: res.append(self.get_Note(string, fret)) return NoteContainer(res)
def find_note_names(self, notelist, string=0, maxfret=24): """Return a list [(fret, notename)] in ascending order. Notelist should be a list of Notes, note-strings or a NoteContainer. Example: >>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4']) >>> t.find_note_names(['...
def get_Note(self, string=0, fret=0, maxfret=24): """Return the Note on 'string', 'fret'. Throw a RangeError if either the fret or string is unplayable. Examples: >>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4']) >>> t,get_Note(0, 0) 'A-3' >>> t.get_N...
def load_img(name): """Load image and return an image object""" fullname = name try: image = pygame.image.load(fullname) if image.get_alpha() is None: image = image.convert() else: image = image.convert_alpha() except pygame.error, message: print ...
def play_note(note): """play_note determines which pad was 'hit' and send the play request to fluidsynth""" index = None if note == Note('B', 2): index = 0 elif note == Note('A', 2): index = 1 elif note == Note('G', 2): index = 2 elif note == Note('E', 2): in...
def play_note(note): """play_note determines the coordinates of a note on the keyboard image and sends a request to play the note to the fluidsynth server""" global text octave_offset = (note.octave - LOWEST) * width if note.name in WHITE_KEYS: # Getting the x coordinate of a white key can...
def add_composition(self, composition): """Add a composition to the suite. Raise an UnexpectedObjectError when the supplied argument is not a Composition object. """ if not hasattr(composition, 'tracks'): raise UnexpectedObjectError("Object '%s' not expected. Expecti...
def set_author(self, author, email=''): """Set the author of the suite.""" self.author = author self.email = email
def set_title(self, title, subtitle=''): """Set the title and the subtitle of the suite.""" self.title = title self.subtitle = subtitle
def set_range(self, range): """Set the range of the instrument. A range is a tuple of two 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 Unexpect...
def note_in_range(self, note): """Test whether note is in the range of this Instrument. Return True if so, False otherwise. """ if type(note) == str: note = Note(note) if not hasattr(note, 'name'): raise UnexpectedObjectError("Unexpected object '%s'. " ...
def can_play_notes(self, notes): """Test if the notes lie within the range of the instrument. Return True if so, False otherwise. """ if hasattr(notes, 'notes'): notes = notes.notes if type(notes) != list: notes = [notes] for n in notes: ...
def play_Note(self, note): """Convert a Note object to a midi event and adds it to the track_data. To set the channel on which to play this note, set Note.channel, the same goes for Note.velocity. """ velocity = 64 channel = 1 if hasattr(note, 'dynamics')...
def play_NoteContainer(self, notecontainer): """Convert a mingus.containers.NoteContainer to the equivalent MIDI events and add it to the track_data. Note.channel and Note.velocity can be set as well. """ if len(notecontainer) <= 1: [self.play_Note(x) for x in noteco...
def play_Bar(self, bar): """Convert a Bar object to MIDI events and write them to the track_data.""" self.set_deltatime(self.delay) self.delay = 0 self.set_meter(bar.meter) self.set_deltatime(0) self.set_key(bar.key) for x in bar: tick = int(ro...
def play_Track(self, track): """Convert a Track object to MIDI events and write them to the track_data.""" if hasattr(track, 'name'): self.set_track_name(track.name) self.delay = 0 instr = track.instrument if hasattr(instr, 'instrument_nr'): self.c...
def stop_Note(self, note): """Add a note_off event for note to event_track.""" velocity = 64 channel = 1 if hasattr(note, 'dynamics'): if 'velocity' in note.dynamics: velocity = note.dynamics['velocity'] if 'channel' in note.dynamics: ...
def stop_NoteContainer(self, notecontainer): """Add note_off events for each note in the NoteContainer to the track_data.""" # if there is more than one note in the container, the deltatime should # be set back to zero after the first one has been stopped if len(notecontainer) <=...
def set_instrument(self, channel, instr, bank=1): """Add a program change and bank select event to the track_data.""" self.track_data += self.select_bank(channel, bank) self.track_data += self.program_change_event(channel, instr)
def header(self): """Return the bytes for the header of track. The header contains the length of the track_data, so you'll have to call this function when you're done adding data (when you're not using get_midi_data). """ chunk_size = a2b_hex('%08x' % (len(self.track_dat...
def midi_event(self, event_type, channel, param1, param2=None): """Convert and return the paraters as a MIDI event in bytes.""" assert event_type < 0x80 and event_type >= 0 assert channel < 16 and channel >= 0 tc = a2b_hex('%x%x' % (event_type, channel)) if param2 is None: ...
def note_off(self, channel, note, velocity): """Return bytes for a 'note off' event.""" return self.midi_event(NOTE_OFF, channel, note, velocity)
def note_on(self, channel, note, velocity): """Return bytes for a 'note_on' event.""" return self.midi_event(NOTE_ON, channel, note, velocity)
def controller_event(self, channel, contr_nr, contr_val): """Return the bytes for a MIDI controller event.""" return self.midi_event(CONTROLLER, channel, contr_nr, contr_val)
def set_deltatime(self, delta_time): """Set the delta_time. Can be an integer or a variable length byte. """ if type(delta_time) == int: delta_time = self.int_to_varbyte(delta_time) self.delta_time = delta_time
def set_tempo(self, bpm): """Convert the bpm to a midi event and write it to the track_data.""" self.bpm = bpm self.track_data += self.set_tempo_event(self.bpm)
def set_tempo_event(self, bpm): """Calculate the microseconds per quarter note.""" ms_per_min = 60000000 mpqn = a2b_hex('%06x' % (ms_per_min / bpm)) return self.delta_time + META_EVENT + SET_TEMPO + '\x03' + mpqn
def time_signature_event(self, meter=(4, 4)): """Return a time signature event for meter.""" numer = a2b_hex('%02x' % meter[0]) denom = a2b_hex('%02x' % int(log(meter[1], 2))) return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer\ + denom + '\x18\x08'
def set_key(self, key='C'): """Add a key signature event to the track_data.""" if isinstance(key, Key): key = key.name[0] self.track_data += self.key_signature_event(key)
def key_signature_event(self, key='C'): """Return the bytes for a key signature event.""" if key.islower(): val = minor_keys.index(key) - 7 mode = '\x01' else: val = major_keys.index(key) - 7 mode = '\x00' if val < 0: val = 256 ...
def track_name_event(self, name): """Return the bytes for a track name meta event.""" l = self.int_to_varbyte(len(name)) return '\x00' + META_EVENT + TRACK_NAME + l + name
def int_to_varbyte(self, value): """Convert an integer into a variable length byte. How it works: the bytes are stored in big-endian (significant bit first), the highest bit of the byte (mask 0x80) is set when there are more bytes following. The remaining 7 bits (mask 0x7F) are used ...
def to_chords(progression, key='C'): """Convert a list of chord functions or a string to a list of chords. Examples: >>> to_chords(['I', 'V7']) [['C', 'E', 'G'], ['G', 'B', 'D', 'F']] >>> to_chords('I7') [['C', 'E', 'G', 'B']] Any number of accidentals can be used as prefix to augment or d...
def determine(chord, key, shorthand=False): """Determine the harmonic function of chord in key. This function can also deal with lists of chords. Examples: >>> determine(['C', 'E', 'G'], 'C') ['tonic'] >>> determine(['G', 'B', 'D'], 'C') ['dominant'] >>> determine(['G', 'B', 'D', 'F'],...
def parse_string(progression): """Return a tuple (roman numeral, accidentals, chord suffix). Examples: >>> parse_string('I') ('I', 0, '') >>> parse_string('bIM7') ('I', -1, 'M7') """ acc = 0 roman_numeral = '' suffix = '' i = 0 for c in progression: if c == '#': ...
def tuple_to_string(prog_tuple): """Create a string from tuples returned by parse_string.""" (roman, acc, suff) = prog_tuple if acc > 6: acc = 0 - acc % 6 elif acc < -6: acc = acc % 6 while acc < 0: roman = 'b' + roman acc += 1 while acc > 0: roman = '#' +...
def substitute_harmonic(progression, substitute_index, ignore_suffix=False): """Do simple harmonic substitutions. Return a list of possible substitions for progression[substitute_index]. If ignore_suffix is set to True the suffix of the chord being substituted will be ignored. Otherwise only progressio...
def substitute_minor_for_major(progression, substitute_index, ignore_suffix=False): """Substitute minor chords for its major equivalent. 'm' and 'm7' suffixes recognized, and ['II', 'III', 'VI'] if there is no suffix. Examples: >>> substitute_minor_for_major(['VI'], 0) ['I'] >>> su...
def substitute_diminished_for_diminished(progression, substitute_index, ignore_suffix=False): """Substitute a diminished chord for another diminished chord. 'dim' and 'dim7' suffixes recognized, and 'VI' if there is no suffix. Example: >>> substitute_diminished_for_diminished(['VII'], 0) [...
def substitute(progression, substitute_index, depth=0): """Give a list of possible substitutions for progression[substitute_index]. If depth > 0 the substitutions of each result will be recursively added as well. Example: >>> substitute(['I', 'IV', 'V', 'I'], 0) ['III', 'III7', 'VI', 'VI7', 'I...
def interval_diff(progression1, progression2, interval): """Return the number of half steps progression2 needs to be diminished or augmented until the interval between progression1 and progression2 is interval.""" i = numeral_intervals[numerals.index(progression1)] j = numeral_intervals[numerals.ind...
def skip(roman_numeral, skip=1): """Skip the given places to the next roman numeral. Examples: >>> skip('I') 'II' >>> skip('VII') 'I' >>> skip('I', 2) 'III' """ i = numerals.index(roman_numeral) + skip return numerals[i % 7]
def add_note(self, note, octave=None, dynamics={}): """Add a note to the container and sorts the notes from low to high. The note can either be a string, in which case you could also use the octave and dynamics arguments, or a Note object. """ if type(note) == str: i...
def add_notes(self, notes): """Feed notes to self.add_note. The notes can either be an other NoteContainer, a list of Note objects or strings or a list of lists formatted like this: >>> notes = [['C', 5], ['E', 5], ['G', 6]] or even: >>> notes = [['C', 5, {'volume': 20}...
def from_chord_shorthand(self, shorthand): """Empty the container and add the notes in the shorthand. See mingus.core.chords.from_shorthand for an up to date list of recognized format. Example: >>> NoteContainer().from_chord_shorthand('Am') ['A-4', 'C-5', 'E-5'] ...
def from_interval(self, startnote, shorthand, up=True): """Shortcut to from_interval_shorthand.""" return self.from_interval_shorthand(startnote, shorthand, up)
def from_interval_shorthand(self, startnote, shorthand, up=True): """Empty the container and add the note described in the startnote and shorthand. See core.intervals for the recognized format. Examples: >>> nc = NoteContainer() >>> nc.from_interval_shorthand('C', '5') ...
def from_progression_shorthand(self, shorthand, key='C'): """Empty the container and add the notes described in the progressions shorthand (eg. 'IIm6', 'V7', etc). See mingus.core.progressions for all the recognized format. Example: >>> NoteContainer().from_progression_shorthan...
def remove_note(self, note, octave=-1): """Remove note from container. The note can either be a Note object or a string representing the note's name. If no specific octave is given, the note gets removed in every octave. """ res = [] for x in self.notes: ...
def remove_notes(self, notes): """Remove notes from the containers. This function accepts a list of Note objects or notes as strings and also single strings or Note objects. """ if type(notes) == str: return self.remove_note(notes) elif hasattr(notes, 'name')...
def remove_duplicate_notes(self): """Remove duplicate and enharmonic notes from the container.""" res = [] for x in self.notes: if x not in res: res.append(x) self.notes = res return res
def transpose(self, interval, up=True): """Transpose all the notes in the container up or down the given interval.""" for n in self.notes: n.transpose(interval, up) return self