def chorale_to_inputs(chorale, voice_ids, index2notes, note2indexes):
    """
    :param chorale: music21 chorale
    :param voice_ids:
    :param index2notes:
    :param note2indexes:
    :return: (num_voices, time) matrix of indexes
    """
    # we cannot assume all parts have the same length
    length = int(chorale.duration.quarterLength * SUBDIVISION)  # in 16th notes
    inputs = []

    # This is to separate chords and melody
    instrument.partitionByInstrument(chorale)
    # we feed input with the melody first
    inputs.append(
        part_to_inputs(chorale.parts[1], length, index2notes[0],
                       note2indexes[0]))
    # We feed input with chords
    inputs.append(roots_to_input(chorale, length, index2notes, note2indexes))
    inputs.append(colors_to_input(chorale, length, index2notes, note2indexes))

    output = np.array(inputs)
    assert len(output.shape) == 2

    return output
Example #2
0
def from_music21(
    stream: Stream,
    resolution=DEFAULT_RESOLUTION
) -> Union[Music, List[Music], Track, List[Track]]:
    """Return a music21 Stream object as Music or Track object(s).

    Parameters
    ----------
    stream : `music21.stream.Stream`
        Stream object to convert.
    resolution : int, optional
        Time steps per quarter note. Defaults to
        `muspy.DEFAULT_RESOLUTION`.

    Returns
    -------
    :class:`muspy.Music` or :class:`muspy.Track`
        Converted Music or Track object(s).

    """
    if isinstance(stream, Opus):
        return from_music21_opus(stream, resolution)
    elif isinstance(stream, Part):
        return from_music21_part(stream, resolution)
    else:
        return from_music21_score(stream, resolution)

    tracks = []
    if isinstance(stream, Score):
        for part in stream.parts:
            instruments = partitionByInstrument(part)
            if instruments:
                for instrument in instruments:
                    tracks.append(parse_track(instrument))
            elif len(part.flat.notesAndRests) > 0:
                tracks.append(parse_track(part))
    else:
        instruments = partitionByInstrument(stream)
        if instruments:
            for instrument in instruments:
                tracks.append(parse_track(instrument))
        elif len(stream.flat.notesAndRests) > 0:
            tracks.append(parse_track(stream))

    return Music(
        metadata=parse_metadata(stream),
        resolution=DEFAULT_RESOLUTION,
        tempos=parse_tempos(stream),
        key_signatures=parse_key_signatures(stream, resolution),
        time_signatures=parse_time_signatures(stream, resolution),
        tracks=tracks,
    )
Example #3
0
def notesPerVerse(midiFile):

    mid = converter.parse(midiFile)

    instruments = instrument.partitionByInstrument(mid)

    assert len(instruments.parts) == 1  # MIDI file must contain only vocals

    for instrument_i in instruments.parts:
        notes_to_parse = instrument_i.recurse()

    n = 8

    notes_to_parse = list(
        filter(
            lambda element: isinstance(element, note.Note) or isinstance(
                element, chord.Chord), notes_to_parse))

    firstBar = int(notes_to_parse[0].offset / 4)

    notesPerCompass = defaultdict(int)
    for element in notes_to_parse:
        start = element.offset
        notesPerCompass[int((start - 4 * firstBar) / n)] += 1

    return list(notesPerCompass.values())
Example #4
0
def get_notes(x="data/Mario/*.mid",
              y='data/Mario/notes',
              save=True,
              integer=True):
    """ Get all the notes and chords from the midi files in the ./data directory """
    notes = []

    for file in glob.glob(x):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try:  # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except:  # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                if (integer == True):
                    notes.append('.'.join(str(n) for n in element.normalOrder))
                else:
                    notes.append('.'.join(str(n) for n in element.pitchNames))
    if (save == True):
        with open(y, 'wb') as filepath:
            pickle.dump(notes, filepath)

    return notes
    def get_notes(MIDI_path):
        """ Get all the notes and chords from the midi files """
        notes = []

        midi_len = len(glob.glob(MIDI_path))
        _length = midi_len if midi_len <= 1000 else 1000
        with tqdm(glob.glob(MIDI_path)[:_length], unit="file") as tglob:
            for file in tglob:
                tglob.set_postfix(name=file)
                # print("Parsing %s" % file)
                try:
                    midi = converter.parse(file)
                except (music21.midi.MidiException, IndexError):
                    continue

                notes_to_parse = None

                try:  # file has instrument parts
                    s2 = instrument.partitionByInstrument(midi)
                    notes_to_parse = s2.parts[0].recurse()
                except Exception:  # file has notes in a flat structure
                    notes_to_parse = midi.flat.notes

                for element in notes_to_parse:
                    if isinstance(element, note.Note):
                        notes.append(str(element.pitch))
                    elif isinstance(element, chord.Chord):
                        notes.append('.'.join(
                            str(n) for n in element.normalOrder))

        print(len(notes))
        return notes
Example #6
0
    def get_notes(self, midi_file):
        notes = []
        chords = []
        notesDict = {n: [] for n in range(self.minNote, self.maxNote)}
        notes_to_parse = None
        parts = instrument.partitionByInstrument(midi_file)

        if parts:  # file has instrument parts
            notes_to_parse = parts.parts[0].recurse()
        else:  # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(element)
            elif isinstance(element, chord.Chord):
                chords.append(element)

        for element in notes:
            if isinstance(element, note.Note):
                if notesDict.__contains__(element.pitch.midi):
                    notesDict[element.pitch.midi] += [[element.offset, element.offset + element.duration.quarterLength]]
        for element in chords:
            if isinstance(element, chord.Chord):
                for item in element:
                    if notesDict.__contains__(item.pitch.midi):
                        notesDict[item.pitch.midi] += [[element.offset, element.offset + element.duration.quarterLength]]

        return notesDict
Example #7
0
def get_notes():
    """ Get all the notes and chords from the midi files in the ./midi_songs directory """
    notes = []

    if os.path.isfile('../data/notes'):
        print("Reading data ...")
        notes = pickle.load(open('../data/notes', 'rb'))
        return notes

    for file in glob.glob(
            "../tutorial/Classical-Piano-Composer/midi_songs/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try:  # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except:  # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('../data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes
Example #8
0
    def get_notes(self):
        """ Get all the notes and chords from the midi files in the directory """
        notes = []
        for file in glob.glob(self.directory + "/*.mid"):
            midi = converter.parse(file)

            print("Parsing %s" % file)

            notes_to_parse = None

            try: # file has instrument parts
                s2 = instrument.partitionByInstrument(midi)
                notes_to_parse = s2.parts[0].recurse() 
            except: # file has notes in a flat structure
                notes_to_parse = midi.flat.notes

            for element in notes_to_parse:
                if isinstance(element, note.Note):
                    notes.append(str(element.pitch) + ' ' + str(element.quarterLength))
                elif isinstance(element, chord.Chord):
                    notes.append('.'.join(str(n) for n in element.normalOrder) + ' ' + str(element.quarterLength))
            
        if len(notes) == 0:
            raise ValueError("No Midi files were found in {} directory".format(self.directory))
            
        with open('notes', 'wb') as filepath:
            pickle.dump(notes, filepath)
    
        return notes
def get_songs():
    songs = []

    for file in glob.glob("data/*.mid"):
        print("Parsing", file)

        try:
            notes = []
            name = os.path.splitext(os.path.basename(file))[0]

            midi = converter.parse(file)
            notes_to_parse = None

            parts = instrument.partitionByInstrument(midi)
            if parts:  # file has instrument parts
                notes_to_parse = parts.parts[0].recurse()
            else:  # file has notes in a flat structure
                notes_to_parse = midi.flat.notes

            for element in notes_to_parse:
                if isinstance(element, note.Note):
                    notes.append(str(element.pitch))
                elif isinstance(element, chord.Chord):
                    notes.append('.'.join(str(n) for n in element.normalOrder))

            songs.append({"name": name, "notes": notes})
        except Exception as err:
            print("Parsing Failed", file)
            print("Error:", err)

    pickle.dump(songs, open("songs.p", "wb"))
    return songs
def get_notes():
    notes = []
    for file in songs:
        # converting .mid file to stream object
        midi = converter.parse(file)
        notes_to_parse = []
        try:
            # Given a single stream, partition into a part for each unique instrument
            parts = instrument.partitionByInstrument(midi)
        except:
            pass
        if parts:  # if parts has instrument parts
            #1 for Format 0 midi files like mond_1.mid and 0 for Format 1 midi files
            notes_to_parse = parts.parts[1].recurse()
        else:
            notes_to_parse = midi.flat.notes
        for element in notes_to_parse:
            # print(element)
            if isinstance(element, note.Note):
                # if element is a note, extract pitch
                notes.append(str(element.pitch))
            elif (isinstance(element, chord.Chord)):
                # if element is a chord, append the normal form of the
                # chord (a list of integers) to the list of notes.
                notes.append('.'.join(str(n) for n in element.normalOrder))
    print("notes", notes)
    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)
    return notes
Example #11
0
def get_notes():
  notes = []

  for file in glob.glob('./data/*.midi'):
    
    stream = converter.parse(file)

    print('Parsing %s' % file)

    notes_to_parse = None

    try: # if the stream has separate instruments, parse the parts separately
        s2 = instrument.partitionByInstrument(stream)
        notes_to_parse = s2.parts[0].recurse() 
    except: # if the file has notes in a flat structure, add them to note_to_parse
        notes_to_parse = stream.flat.notes

    for element in notes_to_parse:
      # if it's a note, add the note to notes
      if isinstance(element, note.Note):
        notes.append(str(element.pitch))
      # if it's a chord, add the chord in normal form
      elif isinstance(element, chord.Chord):
        notes.append('.'.join(str(n) for n in element.normalOrder))
  
  with open('./notes', 'wb') as filepath:
    pickle.dump(notes, filepath)

  print(notes)
  return notes
    def create_notes(self):
        self.notes = []
        for file in glob.glob(self.path + "/*.mid"):
            midi = converter.parse(file)
            parts = instrument.partitionByInstrument(midi)
            notes_to_parse = parts.parts[0].recurse(
            ) if parts else midi.flat.notes
            last_offset_notes = 0
            last_offset_chords = 0
            for element in notes_to_parse:
                if isinstance(element, note.Note):
                    offset = element.offset - last_offset_notes
                    last_offset_notes = element.offset
                    self.notes.append(str(element.pitch) + "," + str(offset))
                elif isinstance(element, chord.Chord):
                    offset = element.offset - last_offset_chords
                    last_offset_chords = element.offset
                    self.notes.append('_'.join(
                        str(n)
                        for n in element.normalOrder) + "," + str(offset))

        # save notes so that loading is faster
        with open(self.name, 'wb') as f:
            pickle.dump(self.notes, f)

        return self.notes
Example #13
0
def get_notes_and_durations():
    """ Get all the notes and chords from the midi files in the ./midi_songs directory
        Also gets the durations"""
    notes = []

    for file in glob.glob('midi_music_pop/*.mid'):
        midi = converter.parse(file)
        notes_to_parse = None
        parts = instrument.partitionByInstrument(midi)
        if parts:
            notes_to_parse = parts.parts[0].recurse()
        else:
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                pitch = str(element.pitch)
                duration = element.duration.quarterLength
                notes.append((pitch, duration))
            elif isinstance(element, chord.Chord):
                pitches = '.'.join(str(n) for n in element.normalOrder)
                duration = element.duration.quarterLength
                notes.append((pitches, duration))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    # print(notes)
    all_durations = [float(x[1]) for x in notes]
    all_durations = set(all_durations)
    return notes
def get_notes():
    """ Get all the notes and chords from the midi files in the ./midi_songs directory """
    notes = []

    for file in glob.glob("midi_songs/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try: # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse() 
        except: # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes
    def parse_midi_file(file_path):
        """
        Reads a MIDI files and parses it to a sequence of notes and chords.
        Note times are discarded, so there may be some notes and chords that are played
        simultaneously that end up following the other in the sequence.  But the goal
        is to end up with a 1 dimensional sequence of notes.

        Ignore rests (isinstance(n, note.Rest), with n.name property)

        :return: list of note/chord strings, and a list of offsets relative to the start of the song
        """
        midi = converter.parse(file_path)
        stream_score = instrument.partitionByInstrument(midi)
        notes_to_parse = stream_score.parts[0].recurse()
        notes, offsets = [], []
        for n in notes_to_parse:
            # append note
            if isinstance(n, note.Note):
                notes.append(str(n.pitch))
                # add offset to set, default to float
                if str(type(n.offset)) == "<class 'fractions.Fraction'>":
                    offsets.append((n.offset.numerator / n.offset.denominator))
                else:
                    offsets.append(n.offset)
            # if chord, append a collapsed string to represent all notes in chord
            elif isinstance(n, chord.Chord):
                notes.append(Processor.collapse_chord_name_to_string(n))
                # add offset to set, default to float
                if str(type(n.offset)) == "<class 'fractions.Fraction'>":
                    offsets.append((n.offset.numerator / n.offset.denominator))
                else:
                    offsets.append(n.offset)

        return notes, offsets
Example #16
0
def identical_pattern(music_score, ngrams=9, consider_rests=False):

    score = music21.converter.parse(music_score)
    notes_list = []
    ngrams_list = list()
    ngrams_dict = {}
    instruments = instrument.partitionByInstrument(score)
    for inst in instruments:
        for note in inst.flat.notesAndRests:
            if consider_rests is True:
                notes_list.append(note.fullName)
            if consider_rests is False:
                if note.isNote:
                    notes_list.append(note.fullName)
        for i, note_listed in enumerate(notes_list):
            for num_ngrams in range(int(ngrams)):
                if i - ngrams + 1 > 0:
                    grams = notes_list[(i - ngrams) + num_ngrams]
                    ngrams_list.append(grams)
            if len(ngrams_list) != 0:
                if tuple(ngrams_list) not in ngrams_dict.keys():
                    ngrams_dict[tuple(ngrams_list)] = 1
                else:
                    ngrams_dict[tuple(ngrams_list)] += 1
            ngrams_list = []
        for w in sorted(ngrams_dict, key=ngrams_dict.get, reverse=True):
            if ngrams_dict[w] > 1 and len(w) is not 0:
                print(w, ngrams_dict[w], inst)
        notes_list = []
Example #17
0
    def generate_segment(self, mid):
        stm_instr = instrument.partitionByInstrument(mid)
        for pt in stm_instr.parts:
            on, off, dur, pitch, vel = self.extract_notes(pt)

            track_dur_sec = pt.seconds  # last release
            track_dur_len = int(math.ceil(track_dur_sec / 0.05))
            segment = [[[0 for k in range(128)] for i in range(track_dur_len)]
                       for j in range(2)]  # 2 x duration x 128

            print("generating... dur: {:.2f}sec || len: {}".format(
                track_dur_sec, track_dur_len))
            # iterate: each note
            for j, note in enumerate(zip(on, off, dur, pitch, vel)):

                x_index = int(note[0] // 0.05)  # time
                y_index = int(note[3])  # pitch

                # onset (binary)
                segment[0][x_index][y_index] = 1

                # note events (velocity)
                for t in range(int(note[2] // 0.05)):
                    # iterate: each 0.05 unit of a single note's duration
                    segment[1][x_index + t][y_index] = int(note[4])

            return segment
Example #18
0
def get_notes():
    """ Parse midi files and return list of songs """
    all_songs = []

    for file in glob.glob("data/*/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        curr_song_notes = []

        notes_to_parse = None

        try:
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except:
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                curr_song_notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                curr_song_notes.append('.'.join(
                    str(n) for n in element.normalOrder))
        all_songs.append(curr_song_notes)

    return all_songs
Example #19
0
def get_notes():
    """ ./midi_songs 디렉토리의 midi 파일에서 모든 노트 및 코드 가져오기 """

    notes = []

    for file in glob.glob("midi_songs/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try: #  악기 부분
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse() 
        except: # flat 부분
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            # Note일 경우
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            # Chord일 경우
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    # 자료형을 파일로 저장
    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes
Example #20
0
def get_notes():
    """ Get all the notes and chords from the midi files in the ./midi_songs directory """
    notes = []
    if os.path.exists("data/notes"):
        return pickle.load(open("data/notes", "rb"))

    for file in glob.glob("midi_songs/*.mid"):
        try:
            midi = converter.parse(file)
        except TypeError:
            print("Invalid file %s" % file)
            continue

        print("Parsing %s" % file)

        notes_to_parse = None

        try:  # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except:  # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes
Example #21
0
def get_notes():
    """ Get all the notes and chords from the midi files in the ./midi_songs directory """
    notes = []
    counter = 0
    for file in glob.glob("source/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try: # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except: # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:

            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
                print(str(element.pitch))
                counter+=1
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)
    print(counter)
    return notes
Example #22
0
def get_musical_notes():
    musical_notes = []

    for file in glob.glob("midi_songs/*.mid"):
        midi = converter.parse(file)

        print("Parsing: %s" % file)

        notes_to_parse = None

        # Instruments?
        try:
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except:
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                musical_notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                musical_notes.append('.'.join(
                    str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(musical_notes, filepath)

    return musical_notes
Example #23
0
def get_notes(file):

    notes = []

    print('Parsing %s...' % file)

    # Parse all midi files within directory.
    midi = converter.parse(file)
    notes_to_parse = None

    # Transpose to the key of C major.
    k = midi.analyze('key')
    i = interval.Interval(k.tonic, pitch.Pitch('C'))
    transposed_midi = midi.transpose(i)

    try:
        # File has instrument parts.
        s2 = instrument.partitionByInstrument(transposed_midi)
        notes_to_parse = s2.parts[0].recurse()
    except Exception:
        # File has notes in a flat structure.
        notes_to_parse = transposed_midi.flat.notes

    for element in notes_to_parse:
        if isinstance(element, note.Note):
            # If element is a note, append pitch name.
            notes.append(str(element.pitch))
        elif isinstance(element, chord.Chord):
            # If element is a chord, append a chain of intervals from root for each note.
            notes.append('.'.join(str(n) for n in element.normalOrder))

    print('File parsed.')

    return notes
def get_notes():
    """
        Get all notes and chords from the midi files in ./midi_songs
    """
    
    notes = []

    for file in glob.glob("midi_songs/*.mid"):
        midi = converter.parse(file)
        notes_to_parse = None

        parts = instrument.partitionByInstrument(midi)

        if parts: # file has instrument parts
            notes_to_parse = parts.parts[0].recurse()
        else: # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    with open('data/notes', 'wb') as f:
        pickle.dump(notes, f)

    return notes
def convert_from_midi():
    notes = []

    for my_file in glob.glob("midi_data/*.mid"):
        midi = converter.parse(my_file)
        notes_to_parse = None

        print("Currently parsing %s" % my_file)

        # if there are instruments in the midi file:
        try:
            parts = instrument.partitionByInstrument(midi)
            notes_to_parse = parts.parts[0].recurse()
        except IOError:
            print("The file has flat structured notes")
            notes_to_parse = midi.flat.notes
        for i in notes_to_parse:
            if isinstance(i, note.Note):
                notes.append(str(i.pitch))
            elif isinstance(i, chord.Chord):
                notes.append('.'.join(str(x) for x in i.normalOrder))

    with open('data/notes', 'wb') as filepath:
        pickle.dump(notes, filepath)

    return notes
Example #26
0
def get_notes():
    notes = []
    for file in glob.glob(MUSIC_PATH):
        print(file)
        cur_song = converter.parse(file)

        print(f'Current song: {file}')

        cur_notes = None

        try:  # instrumental notes
            instr = instrument.partitionByInstrument(cur_song)
            cur_notes = instr.parts[0].recurse()
        except:  # flat notes
            cur_notes = cur_song.flat.notes

        for item in cur_notes:
            if isinstance(item, note.Note):  # single note to append
                notes.append(str(item.pitch))
            elif isinstance(item, chord.Chord):  # chords have multiple notes
                notes.append('.'.join(str(i) for i in item.normalOrder))

    with open(NOTES_PATH, 'wb') as path:
        pickle.dump(notes, path)
    return notes
Example #27
0
def get_notes():
    """ Get all the notes and chords from the midi files """
    notes = []

    #for file in glob.glob("Pokemon MIDIs/*.mid"):
    for file in glob.glob("midi_bts_5/*.mid"):
        midi = converter.parse(file)

        print("Parsing %s" % file)

        notes_to_parse = None

        try:  # file has instrument parts
            s2 = instrument.partitionByInstrument(midi)
            notes_to_parse = s2.parts[0].recurse()
        except:  # file has notes in a flat structure
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))

    return notes
def process_midis(glob_dir):
    notes = set()
    notes_by_file = {}

    for input_file in glob.glob(glob_dir):
        print("Ingesting... %s" % input_file)

        midi = converter.parse(input_file)
        parts = instrument.partitionByInstrument(midi)
        if parts and len(parts) > 0:
            notes_to_parse = parts.parts[0].recurse()
        else:
            notes_to_parse = midi.flat.notes

        file_notes = []
        for element in notes_to_parse:
            if isinstance(element, note.Note):
                file_notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                file_notes.append('.'.join(
                    str(n) for n in element.normalOrder))

        notes_by_file[input_file] = file_notes
        notes.update(set(file_notes))

    return sorted(notes), notes_by_file
Example #29
0
def from_music21_score(score: Score, resolution=DEFAULT_RESOLUTION) -> Music:
    """Return a music21 Stream object as a Music object.

    Parameters
    ----------
    score : `music21.stream.Score`
        Score object to convert.
    resolution : int, optional
        Time steps per quarter note. Defaults to
        `muspy.DEFAULT_RESOLUTION`.

    Returns
    -------
    :class:`muspy.Music`
        Converted Music object.

    """
    tracks = []
    for part in score.parts:
        instruments = partitionByInstrument(part)
        if instruments:
            for instrument in instruments:
                tracks.append(parse_track(instrument))
        elif len(part.flat.notesAndRests) > 0:
            tracks.append(parse_track(part))

    return Music(
        metadata=parse_metadata(score),
        resolution=DEFAULT_RESOLUTION,
        tempos=parse_tempos(score),
        key_signatures=parse_key_signatures(score, resolution),
        time_signatures=parse_time_signatures(score, resolution),
        tracks=tracks,
    )
def midi2image(midi_path,image_path):
    mid = converter.parse(midi_path)

    instruments = instrument.partitionByInstrument(mid)

    data = {}

    try:
        i=0
        for instrument_i in instruments.parts:
            notes_to_parse = instrument_i.recurse()

            if instrument_i.partName is None:
                data["instrument_{}".format(i)] = get_notes(notes_to_parse)
                i+=1
            else:
                data[instrument_i.partName] = get_notes(notes_to_parse)

    except:
        notes_to_parse = mid.flat.notes
        data["instrument_0".format(i)] = get_notes(notes_to_parse)

    resolution = 0.25

    for instrument_name, values in data.items():
        # https://en.wikipedia.org/wiki/Scientific_pitch_notation#Similar_systems
        upperBoundNote = 127
        lowerBoundNote = 21
        maxSongLength = 100

        index = 0
        prev_index = 0
        repetitions = 0
        while repetitions < 1:
            if prev_index >= len(values["pitch"]):
                break

            matrix = np.zeros((upperBoundNote-lowerBoundNote,maxSongLength))

            pitchs = values["pitch"]
            durs = values["dur"]
            starts = values["start"]

            for i in range(prev_index,len(pitchs)):
                pitch = pitchs[i]

                dur = int(durs[i]/resolution)
                start = int(starts[i]/resolution)

                if dur+start - index*maxSongLength < maxSongLength:
                    for j in range(start,start+dur):
                        if j - index*maxSongLength >= 0:
                            matrix[pitch-lowerBoundNote,j - index*maxSongLength] = 255
                else:
                    prev_index = i
                    break
            img_path = image_path + "\\" + midi_path.split("\\")[-1].replace(".mid",f"_{instrument_name}_{index}.png")
            imwrite(img_path,matrix)
            index += 1
            repetitions+=1
def get_notes():
    notes = []
    DIR = 'groove\\dataset'
    num_files = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])
    i = 1
    for file in glob.glob('groove\\dataset\\*.mid'):
        midi = converter.parse(file)

        print("(%s/%s) Parsing %s" % (i, num_files, file))

        notes_to_parse = None
        parts = instrument.partitionByInstrument(midi)

        if parts:
            notes_to_parse = parts.parts[0].recurse()
        else:
            notes_to_parse = midi.flat.notes

        for element in notes_to_parse:
            if isinstance(element, note.Note):
                notes.append(str(element.pitch))
            elif isinstance(element, chord.Chord):
                notes.append('.'.join(str(n) for n in element.normalOrder))
        i = i + 1

        if i > 200:
            break
    return notes
Example #32
0
from music21 import converter, instrument, note, chord
import glob
import numpy as np
import keras
import np_utils
import os

notes = []
print('Generating Notes ...')
for file in glob.glob("./../midi_songs/*.mid"):
    midi = converter.parse(file)
    notes_to_parse = None

    parts = instrument.partitionByInstrument(midi)

    if parts:
        notes_to_parse = parts.parts[0].recurse()
    else:
        notes_to_parse = midi.flat.notes

    for element in notes_to_parse:
        if isinstance(element, note.Note):
            notes.append(str(element.pitch))
        elif isinstance(element, chord.Chord):
            notes.append('.'.join(str(n) for n in element.normalOrder))

print('Notes Generated')
print('Generating Dataset ... ')

pitch_names = sorted(set(item for item in notes))
n_vocab = float(len(pitch_names))