def write(
        self, out,
        title="untitled",  # distinct from filename
        time_signature=(4, 2, 24, 8),  # (2nd arg is power of 2)
        key_signature = (0, 0),  # C
        tempo = 500000  # in microseconds per quarter note
    ):
        num_tracks = 1 + len(self.tracks)
        Thd(format=1, num_tracks=num_tracks, division=16).write(out)
        T = 1  # how to translate events times into time_delta using the division above

        # first track will just contain time/key/tempo info
        t = Trk()

        t0, t1, t2, t3 = time_signature
        t.time_signature(t0, t1, t2, t3)
        k0, k1 = key_signature
        t.key_signature(k0, k1)
        t.tempo(tempo)
        t.sequence_track_name(title)

        t.track_end()
        t.write(out)

        # each track is written to it's own channel
        for channel, track in enumerate(self.tracks):
            t = Trk()

            # set other track attributes here
            #t.instrument('my instrument')

            # set the instrument this channel is set for
            t.program_change(channel, self.instruments[channel])

            # we make a list of events including note off events so we can sort by
            # offset including them (to avoid negative time deltas)
            # @@@ this may eventually be a feature of sequences rather than this
            # MIDI library

            events_with_noteoff = []
            for point in track:
                offset, note_value, duration = point.tuple(OFFSET_64, MIDI_PITCH, DURATION_64)
                velocity = 64 if 'velocity' not in point else point['velocity']
                if note_value is not None:
                    events_with_noteoff.append((True, offset, note_value, velocity))
                    events_with_noteoff.append((False, offset + duration, note_value, velocity))

            prev_offset = None
            for on, offset, note_value, velocity in sorted(events_with_noteoff, key=lambda x: x[1]):
                if prev_offset is None:
                    time_delta = 0
                else:
                    time_delta = (offset - prev_offset) * T
                if on:
                    t.start_note(time_delta, channel, note_value, velocity)
                else:
                    t.end_note(time_delta, channel, note_value)
                prev_offset = offset

            t.track_end()
            t.write(out)
dataset/ETHPy150Open jtauber/sebastian/sebastian/midi/write_midi.py/SMF.write/original