Ejemplo n.º 1
0
def decode_score(encoding, num_measures, ts, image=False):
    score = Stream()
    score.timeSignature = TimeSignature(ts)
    steps_per_measure = len(encoding) / num_measures
    measure_ind = 0
    while measure_ind < num_measures:
        start_beat = int(measure_ind * steps_per_measure)
        end_beat = int((measure_ind + 1) * steps_per_measure)
        measure = Measure()
        for beat_ind in range(start_beat, end_beat):
            if image:
                played_pitches = np.nonzero(encoding[beat_ind])[0]
            else:
                played_pitches = np.nonzero(encoding[beat_ind])
            if len(played_pitches) == 0:
                measure.append(Rest(quarterLength=4.0 / GRANULARITY))
            else:
                played_notes = [
                    midi_to_note(int(pitch + MIN_PITCH))
                    for pitch in played_pitches
                ]
                chord = Chord(played_notes, quarterLength=4.0 / GRANULARITY)
                measure.append(chord)
        score.append(measure)
        measure_ind += 1
    return score
Ejemplo n.º 2
0
def tensors_to_stream(outputs, config, metadata=None):
    cur_measure_number = 0
    parts = {}
    for part_name in outputs.keys():
        if part_name == 'extra':
            continue
        part = Part(id=part_name)
        parts[part_name] = part

    last_time_signature = None
    cur_time_signature = '4/4'
    for step in range(outputs['soprano'].shape[0]):
        extra = outputs['extra'][step]
        if extra[indices_extra['has_time_signature_3/4']].item() == 1:
            cur_time_signature = '3/4'
        elif extra[indices_extra['has_time_signature_4/4']].item() == 1:
            cur_time_signature = '4/4'
        elif extra[indices_extra['has_time_signature_3/2']].item() == 1:
            cur_time_signature = '3/2'
        cur_time_pos = extra[indices_extra['time_pos']].item()
        has_fermata = extra[indices_extra['has_fermata']].item() == 1

        if cur_time_pos == 1.0 or cur_measure_number == 0:
            for part_name, part in parts.items():
                part.append(Measure(number=cur_measure_number))
                if cur_measure_number == 0:
                    if part_name in ['soprano', 'alto']:
                        part[-1].append(clef.TrebleClef())
                    else:
                        part[-1].append(clef.BassClef())
                    key = int(
                        torch.argmax(
                            outputs['extra'][0, indices_extra['has_sharps_0']:
                                             indices_extra['has_sharps_11'] +
                                             1],
                            dim=0).item())
                    if key >= 6:
                        key -= 12
                    part[-1].append(KeySignature(key))
                    part[-1].append(MetronomeMark(number=90))
            cur_measure_number += 1

        if last_time_signature is None or cur_time_signature != last_time_signature:
            for part in parts.values():
                part[-1].append(TimeSignature(cur_time_signature))
            last_time_signature = cur_time_signature

        for part_name, part in parts.items():
            idx = torch.argmax(outputs[part_name][step]).item()
            if idx == indices_parts['is_continued']:
                try:
                    last_element = part[-1].flat.notesAndRests[-1]
                    cur_element = deepcopy(last_element)
                    if last_element.tie is not None and last_element.tie.type == 'stop':
                        last_element.tie = Tie('continue')
                    else:
                        last_element.tie = Tie('start')
                    cur_element.tie = Tie('stop')
                except IndexError:
                    logging.debug(
                        'Warning: "is_continued" on first beat. Replaced by rest.'
                    )
                    cur_element = Rest(quarterLength=config.time_grid)
                part[-1].append(cur_element)
            elif idx == indices_parts['is_rest']:
                part[-1].append(Rest(quarterLength=config.time_grid))
            else:
                pitch = Pitch()
                part[-1].append(Note(pitch, quarterLength=config.time_grid))
                # Set pitch value AFTER appending to measure in order to avoid unnecessary accidentals
                pitch.midi = idx + min_pitches[part_name] - len(indices_parts)

        if has_fermata:
            for part in parts.values():
                fermata = Fermata()
                fermata.type = 'upright'
                part[-1][-1].expressions.append(fermata)

    score = Score()
    if metadata is not None:
        score.append(Metadata())
        score.metadata.title = f"{metadata.title} ({metadata.number})"
        score.metadata.composer = f"Melody: {metadata.composer}\nArrangement: BachNet ({datetime.now().year})"
    for part in parts.values():
        part[-1].rightBarline = 'light-heavy'

    score.append(parts['soprano'])
    if 'alto' in parts:
        score.append(parts['alto'])
        score.append(parts['tenor'])
    score.append(parts['bass'])

    score.stripTies(inPlace=True, retainContainers=True)

    return score
def populate_measures(song):
    # Initial values
    time_signature_length = util.time_signature(song)
    seen_length = 0
    bars = []
    current_bar = []

    # Helper functions

    # Appends an item to a bar
    def append_bar(current_bar, seen_length, item):
        current_bar += [item]
        seen_length += item.duration.quarterLength
        return (current_bar, seen_length)

    # Checks to see if the item finishes the bar
    def check_bar(bars, current_bar, seen_length):
        if seen_length >= time_signature_length:
            bars += [current_bar]
            current_bar = []
            seen_length = 0
        return (bars, current_bar, seen_length)

    # Finds the notes
    def find_bars(part):
        if isinstance(part, Iterable):
            for item in part:
                if type(item) is Note:
                    return part
                else:
                    res = find_bars(item)
                    if res is not None:
                        return res
        return None

    # Find the part which has the notes
    part = find_bars(song)
    # Search through each item in the bar
    for item in part:
        if type(item) is Note:
            # Note
            (current_bar, seen_length) = append_bar(current_bar, seen_length,
                                                    item)
            (bars, current_bar,
             seen_length) = check_bar(bars, current_bar, seen_length)
        elif type(item) is Rest:
            # Rest
            (current_bar, seen_length) = append_bar(current_bar, seen_length,
                                                    item)
            (bars, current_bar,
             seen_length) = check_bar(bars, current_bar, seen_length)

    # LilyPond might forget a rest at the end
    if time_signature_length - seen_length > 0:
        (current_bar, seen_length) = append_bar(
            current_bar, seen_length,
            Rest(quarterLength=time_signature_length - seen_length))
    (bars, current_bar, seen_length) = check_bar(bars, current_bar,
                                                 seen_length)

    # Populate song.elements, which is where the items should have been
    song.elements = []
    for bar in bars:
        measure = Measure()
        for n in bar:
            measure.append(copy.deepcopy(n))
        song.append(measure)
    return song
Ejemplo n.º 4
0
    key_name = key.step.upper() if key.mode == "major" else key.step.lower()

    for note in notes:
      if note.part == key.part and note.measure == key.measure:
        note.step = Interval(noteStart=Note(Key(key_name).asKey().tonic), noteEnd=note._music21_object).semitones % 12

  return notes


if __name__ == "__main__":
  """
  How to create Mupix Objects.
  """
  from music21.stream import Score, Part, Measure
  from music21.key import KeySignature
  from music21.note import Note  # noqa

  s = Score()
  p1 = Part(id="part1")
  m1 = Measure(number=1)
  m1.append(KeySignature(3))
  m1.append(Note("C4", type="eighth"))
  m2 = Measure(number=2)
  m2.append(KeySignature(0))
  m2.append(Note("G4", type="eighth"))
  p1.append([m1, m2])
  s.append([p1])

  notes = [NoteObject(item, 1) for item in s.recurse().notes if not item.isChord]
  print(notes)
Ejemplo n.º 5
0
def generate(tune, clef=m21.clef.TrebleClef()):
    score = m21utils.loadScoreForTune(tune)
    # print 'score', score
    s = score.parts[0].getElementsByClass("Measure")
    m21.harmony.realizeChordSymbolDurations(s)  ## Needed to make this work!
    MyScore = m21.stream.Score()
    MyScore.append(s[0].keySignature)  ## get key from document
    MyScore.append(clef)  #add clef

    for m in s:
        MyMeasure = Measure()  ## Make a measure and put everything inside it
        MyMeasure.number = m.number  ## give the measure a number
        MyMeasure.rightBarline = m.rightBarline
        MyMeasure.leftBarline = m.leftBarline
        # print("_____________________")
        # print("In measure "+ str(m.number) + "(" + str(m.id) + ")" +" of " + str(len(s)) ) #debug monitoring
        c = m.getElementsByClass(ChordSymbol)
        for x in range(len(c)):
            # print(c[x].duration)
            # print(c[x].beat)
            # print (c[x].figure)
            # print("--------------------")
            TheFigure = c[x].figure
            MyChord = Chord(c[x].pitches)
            MySymbol = ChordSymbol()
            ######## Fix XML chord symbols ############
            if (TheFigure.find(" alter b9") != -1):
                MySymbol = m21utils.writeFlatNine(MyMeasure,
                                                  c[x].pitches[0].name,
                                                  c[x].duration,
                                                  c[x].chordKind)
            elif (TheFigure.find(" add b9") != -1):
                MySymbol = m21utils.writeFlatNine(MyMeasure,
                                                  c[x].pitches[0].name,
                                                  c[x].duration,
                                                  c[x].chordKind)
            elif (TheFigure.find(" add #9") != -1):
                MySymbol = m21utils.writeSharpNine(MyMeasure,
                                                   c[x].pitches[0].name,
                                                   c[x].duration,
                                                   c[x].chordKind)
            elif (TheFigure.find(" add #7") != -1):
                MySymbol = m21utils.writeSharpSeven(MyMeasure,
                                                    c[x].pitches[0].name,
                                                    c[x].duration,
                                                    c[x].chordKind)
            elif (TheFigure.find(" add #11") != -1):
                MySymbol = m21utils.writeSharpEleven(MyMeasure,
                                                     c[x].pitches[0].name,
                                                     c[x].duration,
                                                     c[x].chordKind)
            elif (TheFigure.find(" add b13") != -1):
                MySymbol = m21utils.writeFlatThirteen(MyMeasure,
                                                      c[x].pitches[0].name,
                                                      c[x].duration,
                                                      c[x].chordKind)
            elif (TheFigure.find(" add b6") != -1):
                MySymbol = m21utils.writeFlatSix(MyMeasure,
                                                 c[x].pitches[0].name,
                                                 c[x].duration, c[x].chordKind)
            elif (TheFigure.find(" alter b5") != -1):
                MySymbol = m21utils.writeHalfDim(MyMeasure,
                                                 c[x].pitches[0].name,
                                                 c[x].duration, c[x].chordKind)
            elif (TheFigure.find(" alter #5") != -1):
                MySymbol = m21utils.writeSharpFive(MyMeasure,
                                                   c[x].pitches[0].name,
                                                   c[x].duration,
                                                   c[x].chordKind)
            elif (TheFigure.find("pedal") != -1):
                MySymbol = m21utils.writePedal(MyMeasure, c[x].pitches[0].name,
                                               c[x].duration, c[x].chordKind)
            else:
                if (c[x].duration.type != "zero"):
                    if (c[x].root().name != c[x].bass().name):
                        # print (c[x].root().name, c[x].bass().name)
                        MySymbol = ChordSymbol(root=c[x].root(),
                                               bass=c[x].bass(),
                                               kind=c[x].chordKind)
                    else:
                        MySymbol = ChordSymbol(root=c[x].root(),
                                               bass=c[x].root(),
                                               kind=c[x].chordKind)
                        MySymbol.duration = c[x].duration
                        MyMeasure.append(MySymbol)
                        # print("Wrote chord " + str(MySymbol.figure) + "...")
            n3 = Note(MySymbol.third)
            n3.duration = Duration(c[x].duration.quarterLength * 0.50)
            # n3.lyric = '3rd'
            n3.octave = 5
            MyMeasure.append(n3)
            if (MySymbol.containsSeventh()):
                n7 = m21.note.Note(MySymbol.seventh)
                n7.duration = Duration(c[x].duration.quarterLength * 0.50)
                # n7.lyric = '7th'
                n7.octave = 5
                MyMeasure.append(n7)
            else:
                n5 = m21.note.Note(MySymbol.root())
                n5.duration = Duration(c[x].duration.quarterLength * 0.50)
                # n5.lyric = 'R'
                n5.octave = 5
                MyMeasure.append(n5)
            if ((m.number) % 4 == 0):
                sl = m21.layout.SystemLayout(isNew=True)
                MyMeasure.append(sl)
        MyScore.append(MyMeasure)

    # Set metadata
    title = tune + ' - Guide Tone Study'
    MyScore.metadata = m21.metadata.Metadata()
    MyScore.metadata.title = title
    MyScore.metadata.movementName = ' '  # For some reason this works, None and '' don't...
    MyScore.metadata.composer = 'Greg Pascale'

    return MyScore
Ejemplo n.º 6
0
    def __init__(self, ranges=False):
        score = self.score = Score()
        self.instruments = self.i = Instruments()
        self.parts = Parts(self.i)

        # Make Metadata
        timestamp = datetime.datetime.utcnow()
        metadata = Metadata()
        metadata.title = 'Early Montreal'
        metadata.composer = 'Jonathan Marmor'
        metadata.date = timestamp.strftime('%Y/%m/%d')
        score.insert(0, metadata)

        [score.insert(0, part) for part in self.parts.l]
        score.insert(0, StaffGroup(self.parts.l))

        if ranges:
            # Don't make a piece, just show the instrument ranges
            for inst, part in zip(self.instruments.l, self.parts.l):
                measure = Measure()
                measure.timeSignature = TimeSignature('4/4')
                low = Note(inst.lowest_note)
                measure.append(low)
                high = Note(inst.highest_note)
                measure.append(high)
                part.append(measure)
            return

        # 18 to 21 minutes
        piece_duration_minutes = scale(random.random(), 0, 1, 18, 21)

        # Make the "songs"
        songs = []
        total_minutes = 0
        n = 1
        while total_minutes < piece_duration_minutes:
            print 'Song {}'.format(n)
            n += 1
            song = Song(self)
            songs.append(song)
            total_minutes += song.duration_minutes

        # Make notation
        previous_duration = None
        for song in songs:
            for bar in song.bars:
                for part in bar.parts:
                    measure = Measure()
                    if bar.tempo:
                        measure.insert(
                            0,
                            MetronomeMark(number=bar.tempo,
                                          referent=Duration(1)))
                        measure.leftBarline = 'double'
                    if bar.duration != previous_duration:
                        ts = TimeSignature('{}/4'.format(bar.duration))
                        measure.timeSignature = ts

                    # Fix Durations
                    durations = [note['duration'] for note in part['notes']]

                    components_list = split_at_beats(durations)
                    components_list = [
                        join_quarters(note_components)
                        for note_components in components_list
                    ]
                    for note, components in zip(part['notes'],
                                                components_list):
                        note['durations'] = components

                    for note in part['notes']:
                        if note['pitch'] == 'rest':
                            n = Rest()
                        if isinstance(note['pitch'], list):
                            pitches = []
                            for pitch_number in note['pitch']:
                                p = Pitch(pitch_number)
                                # Force all flats
                                if p.accidental.name == 'sharp':
                                    p = p.getEnharmonic()
                                pitches.append(p)
                            n = Chord(notes=pitches)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        else:
                            p = Pitch(note['pitch'])
                            # Force all flats
                            if p.accidental.name == 'sharp':
                                p = p.getEnharmonic()
                            n = Note(p)

                            # TODO add slurs
                            # TODO add glissandos
                            # TODO add -50 cent marks

                        d = Duration()
                        if note['duration'] == 0:
                            d.quarterLength = .5
                            d = d.getGraceDuration()
                        else:
                            d.fill(note['durations'])
                        n.duration = d

                        measure.append(n)

                    self.parts.d[part['instrument_name']].append(measure)
                previous_duration = bar.duration