def notate_note(self, note):
        if note['pitch'] == 'rest':
            n = Rest()
        else:
            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)

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

        d = Duration()
        if note['duration'] == 0:
            d.quarterLength = .125
            d = d.getGraceDuration()
        else:
            d.fill(note['durations'])
        n.duration = d
        return n
def notate_score(musician_names, instrument_names, music):
    score = Score()

    for musician_name, instrument_name in zip(musician_names,
                                              instrument_names):
        instrument = get_instrument(instrument_name)
        instrument.partName = instrument.instrumentName
        instrument.partAbbreviation = instrument.instrumentAbbreviation

        parts = []
        part = Part()
        parts.append(part)
        part.insert(0, instrument)

        score.insert(0, part)
        score.insert(0, StaffGroup(parts))

        notes = music[musician_name]

        for pitches in notes:
            if not pitches or pitches == 'stop':
                note = Rest()
            elif len(pitches) == 1:
                pitch = Pitch(pitches[0] + 60)
                note = Note(pitch)
            else:
                note = Chord(notes=[Pitch(p + 60) for p in pitches])

            duration = Duration()
            duration.fill([4.0])
            note.duration = duration

            part.append(note)

    score.show('musicxml', '/Applications/Sibelius 7.5.app')
Esempio n. 3
0
def to_musicxml(sc_enc):
    "Converts Chord tuples (see chorales.prepare_poly) to musicXML"
    timestep = Duration(1. / FRAMES_PER_CROTCHET)
    musicxml_score = Stream()
    prev_chord = dict() # midi->(note instance from previous chord), used to determine tie type (start, continue, stop)
    for has_fermata, chord_notes in sc_enc:
        notes = []
        if len(chord_notes) == 0: # no notes => rest for this frame
            r = Rest()
            r.duration = timestep
            musicxml_score.append(r)
        else:
            for note_tuple in chord_notes:
                note = Note()
                if has_fermata:
                    note.expressions.append(expressions.Fermata())
                note.midi = note_tuple[0]
                if note_tuple[1]: # current note is tied
                    note.tie = Tie('stop')
                    if prev_chord and note.pitch.midi in prev_chord:
                        prev_note = prev_chord[note.pitch.midi]
                        if prev_note.tie is None:
                            prev_note.tie = Tie('start')
                        else:
                            prev_note.tie = Tie('continue')
                notes.append(note)
            prev_chord = { note.pitch.midi : note for note in notes }
            chord = Chord(notes=notes, duration=timestep)
            if has_fermata:
                chord.expressions.append(expressions.Fermata())
            musicxml_score.append(chord)
    return musicxml_score
Esempio n. 4
0
def make_music21_note(
    pitch_number=None,
    duration=1.0,
    staccato=False,
    tenuto=False,
    accent=False,
    falloff=False,
    plop=False,
    scoop=False,
    doit=False,
    breath_mark=False,
):
    if pitch_number == None or pitch_number == 'rest':
        n = Rest()
    elif isinstance(pitch_number, list):
        pitches = [Pitch(p) for p in pitch_number]
        for p in pitches:
            if p.accidental.name is 'natural':
                p.accidental = None
        n = Chord(pitches)
    else:
        p = Pitch(pitch_number)
        if p.accidental.name is 'natural':
            p.accidental = None
        n = Note(p)

    d = Duration()
    d.quarterLength = duration
    n.duration = d

    if staccato:
        n.articulations.append(Staccato())
    if tenuto:
        n.articulations.append(Tenuto())
    if accent:
        n.articulations.append(Accent())
    if falloff:
        n.articulations.append(Falloff())
    if plop:
        n.articulations.append(Plop())
    if scoop:
        n.articulations.append(Scoop())
    if doit:
        n.articulations.append(Doit())
    if breath_mark:
        n.articulations.append(BreathMark())

    return n
Esempio n. 5
0
    def __init__(self, n, piece, movement, quadlet, couplet, lines):
        self.n = n
        self.piece = piece
        self.movement = movement
        self.quadlet = quadlet
        self.couplet = couplet
        self.lines = lines
        self.duration = quadlet.phrase_duration

        self.first = False
        if n == 1 and couplet.n == 1:
            self.first = True

        for line in lines:
            # print ('.' * int(line['rhythm'][0] * 2)) + ('-' * int(line['rhythm'][1] * 2)) + ('.' * int(line['rhythm'][2] * 2))
            part = piece.parts.d[line['instrument']]

            measure = Measure()
            if self.first and quadlet.previous_phrase_duration != self.duration:
                ts = TimeSignature('{}/4'.format(self.duration), self.duration)

                # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                # for i, b in enumerate(ts.beatSequence):
                #     if b.duration.quarterLength == 4:
                #         ts.beatSequence[i] = b.subdivide(2)
                #         # ts.beatSequence[i][0] = b.subdivide(2)
                #         # ts.beatSequence[i][1] = b.subdivide(2)
                #     elif b.duration.quarterLength == 3:
                #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                #     elif b.duration.quarterLength == 2:
                #         ts.beatSequence[i] = b.subdivide(2)
                measure.timeSignature = ts

            r1_dur, note_dur, r2_dur = line['rhythm']

            line['notes'] = []

            if r1_dur > 0:
                line['notes'].append({
                    'duration': r1_dur,
                    'pitch': 'rest'
                })

            line['notes'].append({
                'duration': note_dur,
                'pitch': line['pitch']
            })

            if r2_dur > 0:
                line['notes'].append({
                    'duration': r2_dur,
                    'pitch': 'rest'
                })

            self.fix_durations(line['notes'])

            for note in line['notes']:
                if note['pitch'] == 'rest':
                    n = Rest()
                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()
                d.fill(note['durations'])
                n.duration = d

                measure.append(n)


            # if r1_dur > 0:
            #     r1 = Rest()
            #     r1.duration = Duration(r1_dur)
            #     measure.append(r1)

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

            # note = Note(p)
            # note.duration = Duration(note_dur)
            # measure.append(note)

            # if r2_dur > 0:
            #     r2 = Rest()
            #     r2.duration = Duration(r2_dur)
            #     measure.append(r2)


            part.append(measure)

        # Put full measure rests in instruments that aren't playing
        playing = [line['instrument'] for line in lines]
        resting = [i for i in piece.instruments.names if i not in playing]

        for i in resting:
            # print '.' * self.duration * 2
            part = piece.parts.d[i]

            measure = Measure()
            if self.first and quadlet.previous_phrase_duration != self.duration:
                ts = TimeSignature('{}/4'.format(self.duration), self.duration)

                # ts.beatSequence.subdivideNestedHierarchy(3)

                # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                # for i, b in enumerate(ts.beatSequence):
                #     if b.duration.quarterLength == 4:
                #         ts.beatSequence[i] = b.subdivide(2)
                #         # ts.beatSequence[i][0] = b.subdivide(2)
                #         # ts.beatSequence[i][1] = b.subdivide(2)
                #     elif b.duration.quarterLength == 3:
                #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                #     elif b.duration.quarterLength == 2:
                #         ts.beatSequence[i] = b.subdivide(2)
                measure.timeSignature = ts

            r = Rest()
            r.duration = Duration(self.duration)
            measure.append(r)

            # fixed_measure = measure.sliceByBeat()
            # part.append(fixed_measure)

            part.append(measure)
Esempio 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
Esempio n. 7
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
Esempio n. 8
0
    def __init__(self, number, piece, movement):
        self.number = number
        self.piece = piece
        self.movement = movement

        instrument_opts = piece.instruments.names[:]

        self.note_opts = {}
        for name in instrument_opts:
            self.note_opts[name] = piece.i.d[name].all_notes

        form = self.form = song_forms.choose()

        self.duration = len(form) * 4

        self.type = 'solo'
        if number % 2:
            self.type = 'ensemble'

        if self.type == 'solo':
            if len(movement.solo_ensemble_options) == 0:
                movement.solo_ensemble_options = piece.i.get_unison_ensembles(min_notes=6)
                print 'Hey, we ran out of unison ensembles! Cool!'
            solo_ensemble_hash = random.choice(movement.solo_ensemble_options.keys())
            self.soloists = movement.solo_ensemble_options[solo_ensemble_hash]['instruments']
            self.soloist_names = [s.nickname for s in self.soloists]
            self.soloists_shared_notes = movement.solo_ensemble_options[solo_ensemble_hash]['notes']
            # Remove chosen ensemble from options
            del movement.solo_ensemble_options[solo_ensemble_hash]

            # remove chosen soloists from instrument options for the song
            for soloist in self.soloist_names:
                instrument_opts.remove(soloist)

            self.accompanist_names = instrument_opts

            len_accompanists = len(self.accompanist_names)
            if len_accompanists == 2:
                ensemble_size = 2
            elif len_accompanists == 3:
                ensemble_size = random.choice([2, 3])
            elif len_accompanists == 4:
                ensemble_size = random.choice([1, 2, 3, 4])

            self.accompanist_names = random.sample(self.accompanist_names, ensemble_size)


        else:
            # who plays, who sits out?
            # ensemble_size = weighted_choice([3, 4, 5, 6], [1, 4, 5, 4])
            # self.ensemble_names = random.sample(instrument_opts, ensemble_size)

            # Everyone plays
            self.ensemble_names = instrument_opts


        # make a phrase for each unique part of the form (eg, an `a` in `abacabac`)
        unique_phrases = []
        for f in set(form):
            if self.type == 'solo':
                PhraseClass = SoloPhrase
            elif self.type == 'ensemble':
                PhraseClass = EnsemblePhrase
            unique_phrases.append(PhraseClass(piece, movement, self))

        # Copy the phrases in the order specified by form
        phrases = []
        for f in form:
            phrases.append(unique_phrases[f])

        # Render phrases as music21 objects
        for phrase in phrases:
            for part in phrase.parts:
                measure = Measure()
                if movement.first_measure:
                    ts = TimeSignature('4/4')

                    # ts.beatSequence = ts.beatSequence.subdivide(4)
                    ts.beamSequence = ts.beamSequence.subdivide(4)


                    # ts.beatSequence.partitionByList(subdivide(self.duration, 4))
                    # for i, b in enumerate(ts.beatSequence):
                    #     if b.duration.quarterLength == 4:
                    #         ts.beatSequence[i] = b.subdivide(2)
                    #         # ts.beatSequence[i][0] = b.subdivide(2)
                    #         # ts.beatSequence[i][1] = b.subdivide(2)
                    #     elif b.duration.quarterLength == 3:
                    #         ts.beatSequence[i] = b.subdivideByList([2, 1])
                    #         # ts.beatSequence[i][0] = ts.beatSequence[i].subdivide(2)
                    #     elif b.duration.quarterLength == 2:
                    #         ts.beatSequence[i] = b.subdivide(2)




                    measure.timeSignature = ts

                    # ts.getBeams()

                self.fix_durations(part['notes'])

                for note in part['notes']:
                    if note['pitch'] == 'rest':
                        n = Rest()
                    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()
                    d.fill(note['durations'])
                    n.duration = d

                    measure.append(n)

                # if len(measure.notesAndRests) > 1:
                #     measure.sliceByBeat(inPlace=True)

                # measure.makeBeams(inPlace=True)

                piece.parts.d[part['instrument_name']].append(measure)
            movement.first_measure = False