'Converts the Melody to NoteSequence proto.
The end of the melody is treated as a NOTE_OFF event for any sustained
notes.
Args:
velocity: Midi velocity to give each note. Between 1 and 127 (inclusive).
instrument: Midi instrument to give each note.
program: Midi program to give each note.
sequence_start_time: A time in seconds (float) that the first note in the
sequence will land on.
qpm: Quarter notes per minute (float).
Returns:
A NoteSequence proto encoding the given melody.'

def to_sequence(self, velocity=100, instrument=0, program=0, sequence_start_time=0.0, qpm=120.0):

    seconds_per_step = ((60.0 / qpm) / self.steps_per_quarter)
    sequence = music_pb2.NoteSequence()
    sequence.tempos.add().qpm = qpm
    sequence.ticks_per_quarter = STANDARD_PPQ
    sequence_start_time += (self.start_step * seconds_per_step)
    current_sequence_note = None
    for (step, note) in enumerate(self):
        if (MIN_MIDI_PITCH <= note <= MAX_MIDI_PITCH):
            if (current_sequence_note is not None):
                current_sequence_note.end_time = ((step * seconds_per_step) + sequence_start_time)
            current_sequence_note = sequence.notes.add()
            current_sequence_note.start_time = ((step * seconds_per_step) + sequence_start_time)
            current_sequence_note.pitch = note
            current_sequence_note.velocity = velocity
            current_sequence_note.instrument = instrument
            current_sequence_note.program = program
        elif (note == MELODY_NOTE_OFF):
            if (current_sequence_note is not None):
                current_sequence_note.end_time = ((step * seconds_per_step) + sequence_start_time)
                current_sequence_note = None
    if (current_sequence_note is not None):
        current_sequence_note.end_time = ((len(self) * seconds_per_step) + sequence_start_time)
    if sequence.notes:
        sequence.total_time = sequence.notes[(-1)].end_time
    return sequence
