readme_example/
readme_example.rs

1use std::error::Error;
2use std::fs::File;
3use std::result::Result;
4
5use rust_music::{
6    compute_pitch, dynamic::*, rhythm::*, Accidental, Instrument, Note, NoteName, Part, Phrase,
7    Score, Tempo,
8};
9
10fn main() -> Result<(), Box<dyn Error>> {
11    // Create a musical phrase that plays C-E-G (arpeggiated C Major chord)
12    // with crotchets, at MezzoForte volume
13    let mut phrase_to_repeat = Phrase::new();
14    phrase_to_repeat.add_note(Note::new(
15        compute_pitch(NoteName::C, Accidental::Natural, 4)?,
16        CROTCHET,
17        MF,
18    )?);
19    phrase_to_repeat.add_note(Note::new(
20        compute_pitch(NoteName::E, Accidental::Natural, 4)?,
21        CROTCHET,
22        MF,
23    )?);
24    phrase_to_repeat.add_note(Note::new(
25        compute_pitch(NoteName::G, Accidental::Natural, 4)?,
26        CROTCHET,
27        MF,
28    )?);
29
30    // Create a piano part that plays the phrase from beat 0
31    let mut piano_part = Part::new(Instrument::AcousticGrandPiano);
32    piano_part.add_phrase(phrase_to_repeat.clone(), 0.);
33
34    // Create a Strings part that plays the phrase from beat 0.5
35    // (at the same time as the piano but shifted half a beat)
36    let mut violins_part = Part::new(Instrument::StringEnsemble1);
37    violins_part.add_phrase(phrase_to_repeat, 0.5);
38
39    // Create a score with a tempo of 60 (one beat per second) and add both parts
40    let mut score = Score::new("my score", Tempo::new(60)?, None);
41    score.add_part(piano_part);
42    score.add_part(violins_part);
43
44    // Write the score to a MIDI file for playback
45    score.write_midi_file(File::create("readme_example.mid")?)?;
46    Ok(())
47}