Crate midi_reader_writer

Source
Expand description

Facilitate reading and writing midi files. This library does not serialise or deserialise midi files, but uses another library for that. Currently supported is using the midly library, behind the engine-midly-0-5 feature.

In particular this create supports,

  • creating an iterator over all the tracks, merged;
  • given an iterator, separating the tracks, and
  • converting time stamps from ticks to microseconds and vice versa.

§Example

The following example illustrates the steps that could typically be used in an application that transforms midi data.

Note: this example requires the convert-time feature, the engine-midly-0-5 feature, and the read feature.

use midi_reader_writer::{
    ConvertTicksToMicroseconds, ConvertMicroSecondsToTicks,
    midly_0_5::{exports::Smf, merge_tracks, TrackSeparator},
};
use std::{fs, error::Error, convert::TryFrom};

fn example(input_filename: &str, output_filename: &str) -> Result<(), Box<dyn Error>> {
    // Read the midi file
    let bytes = fs::read(input_filename)?;
    let input_midi_file = Smf::parse(&bytes)?;


    let mut ticks_to_microseconds = ConvertTicksToMicroseconds::try_from(input_midi_file.header)?;
    let mut microseconds_to_ticks = ConvertMicroSecondsToTicks::from(input_midi_file.header);
    let mut separator = TrackSeparator::new();

    // Iterate over the events from all tracks:
    for (ticks, track_index, event) in merge_tracks(&input_midi_file.tracks) {

        // Convert the ticks to microseconds:
        let microseconds = ticks_to_microseconds.convert(ticks, &event);

        // Do something with the event or with the timing, or both, or ...
        // ... <- Insert your code here

        // Convert from microseconds to ticks:
        let new_ticks = microseconds_to_ticks.convert(microseconds, &event)?;

        // Push the event to the appropriate track.
        separator.push(ticks, track_index, event)?;
    }

    // Save the output:
    let tracks = separator.collect();
    let output_midi_file = Smf {
        header: input_midi_file.header,
        tracks,
    };
    output_midi_file.save(output_filename)?;
    Ok(())
}

Modules§

midly_0_5
Everything specific to using this crate with the midly crate, version 0.5.x, behind the engine-midly-0-5 feature.

Structs§

ConvertMicroSecondsToTicks
Convert timings of midi events from microseconds to ticks.
ConvertTicksToMicroseconds
Convert timings of midi events from ticks to microseconds.

Enums§

TimeConversionError
Error type for failed time conversions.

Traits§

MidiEvent
Implement this trait to use ConvertTicksToMicroseconds and ConvertMicroSecondsToTicks for this type of midi event.