Expand description
§Overview
midly
is a full-featured MIDI parser and writer, focused on performance.
Parsing a .mid
file can be as simple as:
use midly::Smf;
let smf = Smf::parse(include_bytes!("../test-asset/Clementi.mid")).unwrap();
for (i, track) in smf.tracks.iter().enumerate() {
println!("track {} has {} events", i, track.len());
}
§Parsing Standard Midi Files (.mid
files)
Parsing Standard Midi Files is usually done through the Smf
struct (or if
working in a no_std
environment without an allocator, through the parse
function).
Note that most types in this crate have a lifetime parameter, because they reference the bytes in the original file (in order to avoid allocations). For this reason, reading a file and parsing it must be done in two separate steps:
use std::fs;
use midly::Smf;
// Load bytes into a buffer
let bytes = fs::read("test-asset/Clementi.mid").unwrap();
// Parse bytes in a separate step
let smf = Smf::parse(&bytes).unwrap();
§Writing Standard Midi Files
Saving .mid
files is as simple as using the Smf::save
method:
// Parse file
let bytes = fs::read("test-asset/Clementi.mid").unwrap();
let smf = Smf::parse(&bytes).unwrap();
// Rewrite file
smf.save("test-asset/ClementiRewritten.mid").unwrap();
SMF files can also be written to an arbitrary writer:
let mut in_memory = Vec::new();
smf.write(&mut in_memory).unwrap();
println!("midi file fits in {} bytes!", in_memory.len());
§Parsing standalone MIDI messages
When using an OS API such as midir
,
LiveEvent
can be used to parse the raw MIDI bytes:
use midly::{live::LiveEvent, MidiMessage};
fn on_midi(event: &[u8]) {
let event = LiveEvent::parse(event).unwrap();
match event {
LiveEvent::Midi { channel, message } => match message {
MidiMessage::NoteOn { key, vel } => {
println!("hit note {} on channel {}", key, channel);
}
_ => {}
},
_ => {}
}
}
§Writing standalone MIDI messages
Raw MIDI message bytes can be produced for consumption by OS APIs, such as
midir
, through the
LiveEvent::write
method:
use midly::{live::LiveEvent, MidiMessage};
fn note_on(channel: u8, key: u8) {
let ev = LiveEvent::Midi {
channel: channel.into(),
message: MidiMessage::NoteOn {
key: key.into(),
vel: 127.into(),
},
};
let mut buf = Vec::new();
ev.write(&mut buf).unwrap();
write_midi(&buf[..]);
}
§About features
The following cargo features are available to enable or disable parts of the crate:
-
parallel
(enabled by default)This feature enables the use of multiple threads when parsing large midi files.
Disabling this feature will remove the dependency on
rayon
. -
std
(enabled by default)This feature enables integration with
std
, for example implementingstd::error::Error
formidly::Error
, support for writing tostd::io::Write
streams, among others.Disabling this feature will make the crate
no_std
. -
alloc
(enabled by default)This feature enables allocations both for ergonomics and performance.
Disabling both the
std
and thealloc
feature will make the crate fullyno_std
, but will reduce functionality to a minimum. For example, theSmf
type is unavailable without thealloc
feature. All types that are unavailable when a feature is disabled are marked as such in their documentation. -
strict
By default
midly
will attempt to plow through non-standard and even obviously corrupted files, throwing away any unreadable data, or even entire tracks in the worst scenario. By enabling thestrict
feature the parser will reject uncompliant data and do additional checking, throwing errors of the kindErrorKind::Malformed
when such a situation arises.
Modules§
- io
- Provides abstractions over writers, even in
no_std
environments. - live
- Provides utilities to read and write “live” MIDI messages produced in real-time, in contrast
with “dead” MIDI messages as stored in a
.mid
file. - num
- Exotically-sized integers used by the MIDI standard.
- stream
- Provides support for the niche use case of reading MIDI events from a non-delimited stream.
Macros§
- stack_
buffer - Define a stack buffer type, suitable for use with
MidiStream
.
Structs§
- Arena
- Helps overcome limitations of the lifetime system when constructing MIDI events and files.
- Error
- Represents an error while parsing an SMF file or MIDI stream.
- Event
Bytemap Iter - An iterator over the events of a single track that keeps track of the raw bytes that make up
each event.
Created by the
EventIter::bytemapped
method. - Event
Iter - An iterator over the events of a single track.
Yielded by the
TrackIter
iterator. - Header
- A MIDI file header, indicating metadata about the file.
- Pitch
Bend - The value of a pitch bend, represented as 14 bits.
- Smf
- Represents a single
.mid
Standard Midi File. If you’re casually looking to parse a.mid
file, this is the type you’re looking for. - SmfBytemap
- A
.mid
Standard Midi File, but keeps a mapping to the raw bytes that make up each event. - Smpte
Time - A timestamp encoding an SMPTE time of the day.
- Track
Event - Represents a parsed SMF track event.
- Track
Iter - An iterator over all tracks in a Standard Midi File.
Created by the
parse
function.
Enums§
- Error
Kind - The type of error that occurred while parsing.
- Format
- The order in which tracks should be laid out when playing back this SMF file.
- Fps
- One of the four FPS values available for SMPTE times, as defined by the MIDI standard.
- Meta
Message - A “meta message”, as defined by the SMF spec. These events carry metadata about the track, such as tempo, time signature, copyright, etc…
- Midi
Message - Represents a MIDI message, usually associated to a MIDI channel.
- Timing
- The timing for an SMF file. This can be in ticks/beat or ticks/second.
- Track
Event Kind - Represents the different kinds of SMF events and their associated data.
Functions§
- parse
- Parse a raw MIDI file lazily, yielding its header and a lazy track iterator. No allocations are made.
- write
- Encode and write a generic MIDI file into the given generic writer. The MIDI file is represented by a header and a list of tracks.
- write_
std - Similar to
write
, but writes to astd::io::Write
writer instead of amidly::io::Write
writer.
Type Aliases§
- Bytemapped
Track - A track, represented as a
Vec
of events along with their originating bytes. - Result
- The result type used by the MIDI parser.
- Track
- A single track: simply a list of track events.