midly icon indicating copy to clipboard operation
midly copied to clipboard

Add examples on how to write LiveEvents to mid files

Open Qualphey opened this issue 1 year ago • 3 comments

I'm trying to write events, coming from jack midi input port, to a mid file. I guess I could say I'm trying to record a midi sequence. The documentation doesn't really have much info nor any examples on how to write live event sequences to mid files.

I still tried and couldn't figure out how to convert LiveEvent to TrackEvent, so I could write it.

I've set up an SMF:

let header = midly::Header {
  format: midly::Format::SingleTrack, // Replace with the desired format
  timing: midly::Timing::Metrical(480.into()), // Replace with the desired timing information
};
let smf = midly::Smf::new(header);

and then tried to push an event to the first track:

let arena = midly::Arena::new();    
...
let live_event = LiveEvent::parse(data).unwrap();
smf.tracks[0].push(live_event.as_track_event(&arena));

But as_track_event returns TrackEventKind and I can't find no way to convert that.

Qualphey avatar Jan 03 '24 20:01 Qualphey

Also I wonder if it's possible to write mid files streaming chunks of event data instead of writing the whole file at once. This way you could save up some memory space especially when you've got many tracks or making long recordings.

Qualphey avatar Jan 04 '24 14:01 Qualphey

The reason why a LiveEvent converts into a TrackEventKind instead of a TrackEvent is that:

TrackEvent = TrackEventKind + (timing info)

Timing info is not so easy to work with in MIDI, but it involves adding a timing message at the beggining of track 0 which defines the unit of time used in the file (a "tick"), and then converting the times at which the events happen to delta ticks.

I agree it would be nice to have a set of examples. If I have some spare time I will add some. If you (or any reader) has figured it out and has some spare time, feel free to add examples.

kovaxis avatar Jan 25 '24 13:01 kovaxis

I've figured this one out. Managed to make a working POC where midi events can be recorded and saved to a .mid file and then played back. Now I'm reworking the code to use multi-threading to queue/fire events on one thread and write/read on another. I might as well post some examples here after I'm done.

Qualphey avatar Jan 25 '24 16:01 Qualphey