Skip to main content

Stream

Struct Stream 

Source
pub struct Stream { /* private fields */ }
Expand description

An ordered stream of music, which may hold other streams.

Implementations§

Source§

impl Stream

Source

pub fn analyze(&self, method: &str) -> Result<Option<Analysis>>

The analysis a method name asks for: music21’s analyze.

ambitus, span and range give the interval from the lowest pitch sounding to the highest; key and the names of music21’s five key weightings give the key the stream is most likely in. The name need not be exact, music21 searching its own names three times over and loosest last, so kostka finds Temperley’s profile and a bare key finds Aarden’s, which is music21’s default.

use music21_rs::stream::Analysis;
use music21_rs::{Note, Stream};

let mut line = Stream::new();
for name in ["C4", "E4", "G4", "C5"] {
    line.push(Note::from_name(name)?);
}
let Some(Analysis::Ambitus(span)) = line.analyze("ambitus")? else {
    panic!("an ambitus")
};
assert_eq!(span.short_name(), "P8");

let Some(Analysis::Key(key)) = line.analyze("key")? else {
    panic!("a key")
};
assert_eq!(key.tonic_pitch_name_with_case(), "C");

// A stream with no pitches has no ambitus.
assert!(Stream::new().analyze("ambitus")?.is_none());

A stream with no pitches has no ambitus and answers nothing for one, as music21 answers None; a key analysis of one refuses, which is what music21 raises on.

§Errors

A method name no analysis answers to, as music21 raises on one, or a key no weighting could settle on.

Source

pub fn is_twelve_tone(&self) -> bool

Whether every pitch sounding is one of the twelve of equal temperament: music21’s isTwelveTone.

A stream with no pitches is, as music21 answers for one.

use music21_rs::{Note, Stream};

let mut line = Stream::new();
line.push(Note::from_name("G#4")?);
assert!(line.is_twelve_tone());
line.push(Note::from_name("G~4")?);
assert!(!line.is_twelve_tone());
Source

pub fn notes_and_rests(&self) -> Vec<(FloatType, StreamElement)>

Every note, rest and chord on the flattened timeline: music21’s flatten().notesAndRests.

Self::notes leaves the rests out, as music21’s notes does. For what the stream holds itself rather than the whole nesting, ask Self::elements_of_class for GeneralNote, which is music21’s own notesAndRests.

use music21_rs::{Duration, KeySignature, Note, Rest, Stream};

let mut line = Stream::new();
line.insert(0.0, KeySignature::new(2));
line.push(Note::from_name("C4")?);
line.push(Rest::new(Duration::quarter()));
// The key signature is left out and the rest kept.
assert_eq!(line.notes_and_rests().len(), 2);
assert_eq!(line.notes().len(), 1);
Source§

impl Stream

Source

pub fn chordify(&self) -> Result<Stream>

The stream as one line of chords, as music21’s chordify makes it: Stream::chordify_with with music21’s defaults.

use music21_rs::{Duration, Note, Stream, StreamKind};

let mut upper = Stream::with_kind(StreamKind::Part);
upper.push(Note::from_name("E4")?.with_duration(Duration::half()));
let mut lower = Stream::with_kind(StreamKind::Part);
lower.push(Note::from_name("C4")?.with_duration(Duration::quarter()));
lower.push(Note::from_name("G3")?.with_duration(Duration::quarter()));
let mut score = Stream::with_kind(StreamKind::Score);
score.insert(0.0, upper);
score.insert(0.0, lower);

let chords = score.chordify()?;
let names: Vec<String> = chords
    .pitches()
    .iter()
    .map(|pitch| pitch.name_with_octave())
    .collect();
assert_eq!(names, ["C4", "E4", "G3", "E4"]);
§Errors

A score that cannot be turned to sounding pitch, or a length no duration has.

Source

pub fn chordify_with(&self, options: &ChordifyOptions) -> Result<Stream>

The stream as one line of chords: at every point where a note, chord or rest in any part starts or stops, a chord of every pitch sounding there, or a rest where none is.

The result is laid out as the first part is – its measures, clefs, keys, meters and the rest of what it holds, but none of its notes, rests or voices – and each measure is made from the measure at the same place in every part. A note sounding on past the end of a chord is tied into the next, a pitch sounding in two parts at once is one note, and a chord carries the articulations and expressions its notes do, one of each kind. Rests standing together in a measure are one rest. A chord symbol’s notes sound where it stands, as music21’s do. Spanners and the lyrics of the notes are not carried across, and every accidental is left for the notation to decide again.

§Errors

As Stream::chordify.

Source§

impl Stream

Source

pub fn find_consecutive_notes( &self, options: &ConsecutiveOptions, ) -> Result<Vec<Option<usize>>>

The notes and chords that follow one another in this stream, as positions in Stream::leaves, with None wherever the line breaks: music21’s findConsecutiveNotes.

Each stream is read on its own, its contents in order, and the line breaks at a rest, at time with nothing in it, at a chord when chords are skipped, and where one stream starts before the one read before it ended – the second voice of a measure, the second part of a score. A note starting before the one before it ends is left out. options changes each of those. A chord of one note is passed over, as are unpitched strokes; a chord symbol counts as a chord. The list never ends on a break.

§Errors

A chord symbol whose notes cannot be worked out.

Source

pub fn melodic_intervals( &self, options: &ConsecutiveOptions, ) -> Result<Vec<MelodicInterval>>

The interval between each two notes Stream::find_consecutive_notes finds next to each other, with no break between them: music21’s melodicIntervals. An interval to or from a chord is taken from the chord’s first note.

use music21_rs::stream::ConsecutiveOptions;
use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("3/4 c4 d' r b b'")?;
let names: Vec<String> = line
    .melodic_intervals(&ConsecutiveOptions::default())?
    .iter()
    .map(|step| step.interval().short_name())
    .collect();
assert_eq!(names, ["M9", "P8"]);
§Errors

As Stream::find_consecutive_notes, or two notes no interval can be spelled between.

Source

pub fn harmonic_intervals( &self, other: &Stream, ) -> Vec<(usize, Option<Interval>)>

For each note this stream holds itself, by its index here, the interval from it to the first note of other sounding where it starts – starting there, or sounding on to it or ending there – that an interval can be taken to: what music21’s attachIntervalsBetweenStreams attaches to each note as its harmonicInterval. None where no note of other sounds.

use music21_rs::tinynotation::from_tiny_notation;

let upper = from_tiny_notation("4/4 e'2 d'2")?.flatten();
let lower = from_tiny_notation("4/4 c1")?.flatten();
let names: Vec<_> = upper
    .harmonic_intervals(&lower)
    .into_iter()
    .map(|(_, interval)| interval.map(|interval| interval.name()))
    .collect();
let expected = ["Major Tenth", "Major Ninth"].map(|name| Some(name.to_string()));
assert_eq!(names, expected);
Source§

impl Stream

Source

pub fn extend_ties(&mut self, ignore_rests: bool)

Ties each note to a note of the same name and octave that starts where it ends, a chord’s notes each to its own, as music21’s extendTies does. With ignore_rests, a note is tied to the next note whatever lies between.

use music21_rs::tinynotation::from_tiny_notation;

let mut line = from_tiny_notation("4/4 c4 c4 d4 d4")?;
line.extend_ties(false);
let ties: Vec<_> = line
    .notes()
    .iter()
    .map(|(_, note)| match note {
        music21_rs::StreamElement::Note(note) => note.tie().map(|tie| tie.tie_type()),
        _ => None,
    })
    .collect();
assert_eq!(ties[0], Some(music21_rs::notation::TieType::Start));
assert_eq!(ties[1], Some(music21_rs::notation::TieType::Stop));
Source

pub fn scale_offsets( &self, amount: FloatType, anchor: Anchor, nested: Anchor, ) -> Result<Stream>

A copy of the stream with each element’s offset scaled by amount from the anchor, and those of the streams it holds from theirs, as music21’s scaleOffsets does.

§Errors

An amount of nought or less.

Source

pub fn scale_durations(&self, amount: FloatType) -> Result<Stream>

A copy of the stream with every length scaled by amount, those in the streams it holds too: music21’s scaleDurations.

§Errors

An amount of nought or less, or a length no duration has.

Source

pub fn augment_or_diminish(&self, amount: FloatType) -> Result<Stream>

A copy of the stream with its offsets scaled from the first element and its lengths scaled, by amount: music21’s augmentOrDiminish.

use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("4/4 c4 d8 e8")?;
let longer = line.augment_or_diminish(2.0)?;
assert_eq!(longer.notes()[2].0, 3.0);
§Errors

As Stream::scale_durations.

Source

pub fn invert_diatonic(&self, inversion: Option<&Pitch>) -> Result<Stream>

A copy of the stream with each note turned upside down about inversion (C4 where none is given) by step, its accidental that of the key – the stream’s one key signature, the one in force at the note where it has several, C major where it has none: music21’s invertDiatonic. A chord’s notes are left as they are.

§Errors

A note turned past the steps a pitch can stand on.

Source

pub fn shift_elements( &mut self, offset: FloatType, start: Option<FloatType>, end: Option<FloatType>, )

Moves the elements this stream holds itself, those starting at or after start and before end where given, by offset: music21’s shiftElements.

Source

pub fn repeat_append(&mut self, element: &StreamElement, times: usize)

Appends a copy of element this many times, each after the last: music21’s repeatAppend.

Source

pub fn repeat_insert(&mut self, element: &StreamElement, offsets: &[FloatType])

Puts a copy of element at each of offsets: music21’s repeatInsert.

Source

pub fn insert_and_shift(&mut self, offset: FloatType, element: StreamElement)

Puts element at offset, first moving everything from the element nearest after that offset onwards far enough that it starts where the new element ends: music21’s insertAndShift.

Source

pub fn bar_duration_proportion( &self, meter: Option<&TimeSignature>, ) -> Result<FloatType>

How much of its bar a measure fills, as a proportion: music21’s barDurationProportion. The bar is that of the measure’s own time signature, or of meter where it has none; failing both, of the time signature that best fits its notes (best_time_signature), and failing that the measure’s own length.

§Errors

A time signature whose bar cannot be worked out, or a bar of no length: an empty measure with no time signature.

Source

pub fn pad_as_anacrusis( &mut self, meter: Option<&TimeSignature>, use_initial_rests: bool, ) -> Result<()>

Pads a measure that does not fill its bar on the left by what it lacks, as a pickup: music21’s padAsAnacrusis. With use_initial_rests, the rests it starts with are taken out first and what follows moved back. The bar is as Stream::bar_duration_proportion has it.

§Errors

A time signature whose bar cannot be worked out.

Source§

impl Stream

Source

pub fn final_barline(&self) -> Option<&Barline>

The barline this stream ends with: music21’s finalBarline for a stream that is not part-like.

It is the right barline of the last measure the stream holds, or a measure’s own right barline, and nothing for a stream holding no measures at all. music21 answers a list for a score or anything else holding part-like streams, which is Self::final_barlines.

use music21_rs::bar::{Barline, BarlineType};
use music21_rs::{Stream, StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
for bar_type in [BarlineType::Double, BarlineType::Final] {
    let mut measure = Stream::with_kind(StreamKind::Measure);
    measure.set_right_barline(Some(Barline::new(bar_type)));
    part.push(measure);
}
assert_eq!(
    part.final_barline().map(Barline::bar_type),
    Some(BarlineType::Final)
);

// A stream holding no measures has none, as music21 answers.
assert!(Stream::new().final_barline().is_none());
Source

pub fn final_barlines(&self) -> Vec<Option<&Barline>>

The barline each part-like stream ends with: music21’s finalBarline for a score, which answers one barline per part.

A stream holding no part-like streams answers nothing, where Self::final_barline answers for the stream itself.

Source

pub fn set_final_barline(&mut self, barline: Option<Barline>)

Writes the barline the stream ends with: music21’s finalBarline setter.

On a stream holding part-like streams every part takes it, as music21’s setter gives each part the one barline it was handed. On any other stream it goes on the last measure, or on a measure itself; a stream with no measures to carry it is left alone, as music21 leaves it.

Source

pub fn staff_lines(&self) -> i64

How many lines this stream’s staff has: music21’s staffLines.

It is read from the first staff layout standing at the start of the stream, however deep, that says a number of lines; five where none does, which is the ordinary staff. A layout standing anywhere after the start says nothing about it, as in music21.

use music21_rs::layout::{Layout, StaffLayout};
use music21_rs::{Stream, StreamElement, StreamKind};

let mut measure = Stream::with_kind(StreamKind::Measure);
assert_eq!(measure.staff_lines(), 5);

let staff = StaffLayout {
    staff_lines: Some(1),
    ..StaffLayout::default()
};
measure.insert(0.0, StreamElement::Layout(Layout::Staff(staff)));
assert_eq!(measure.staff_lines(), 1);

// A part reads the layout of the measure it starts with.
let mut part = Stream::with_kind(StreamKind::Part);
part.push(measure);
assert_eq!(part.staff_lines(), 1);
Source§

impl Stream

Source

pub fn extend_duration(&self, classes: &[&str]) -> Result<Stream>

A copy of the stream with each element of a class stretched to where the next one starts: music21’s extendDuration.

The last one reaches the end of the stream. Elements of other classes are left alone and do not break the run, so a dynamic standing between two notes does not stop the first note reaching the second.

Only what the crate gives a length to is stretched: a note, a rest, a chord or a chord symbol. music21 would stretch any element, since everything there carries a duration – extendDuration(Dynamic) gives the dynamic a length – where the crate keeps the marks that say what is in force from a point timeless. Asking for one of those classes leaves the stream as it stands.

use music21_rs::{Dynamic, Note, Stream};

let mut line = Stream::new();
for place in [0.0, 10.0, 20.0] {
    line.insert(place, Note::from_name("C4")?);
}
line.insert(15.0, Dynamic::new("ff"));

let stretched = line.extend_duration(&["GeneralNote"])?;
let lengths: Vec<f64> = stretched
    .notes()
    .iter()
    .map(|(_, note)| note.quarter_length())
    .collect();
// Ten to the next note, ten again past the dynamic, and the last
// keeps the length it came with to the end of the stream.
assert_eq!(lengths, [10.0, 10.0, 1.0]);
§Errors

A length no written value can be made of.

Source

pub fn merge_elements(&mut self, other: &Stream, classes: Option<&[&str]>)

Takes in everything another stream holds, each at the offset it stands at there: music21’s mergeElements.

With classes, only the elements answering to one of those music21 class names come. music21 stores the other stream’s own objects in both streams; a crate stream owns what it holds, so they are copied.

use music21_rs::{Note, Stream};

let mut from = Stream::new();
from.insert(0.0, Note::from_name("F#4")?);
from.insert(1.0, Note::from_name("G4")?);

let mut into = Stream::new();
into.merge_elements(&from, None);
assert_eq!(into.len(), 2);
Source

pub fn clone_empty(&self) -> Stream

A stream like this one holding nothing: music21’s cloneEmpty.

It is of the same kind and carries what music21’s mergeAttributes copies: the id – and only where one was given, music21 leaving an object’s own address behind, which a crate stream has nothing of – whether the stream is at sounding pitch, a measure’s number, suffix and padding, and a part’s name and abbreviation. Nothing else comes: not the metadata, the barlines or the spanners, which Stream::template keeps.

use music21_rs::{Note, Stream, StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
part.set_id(Some("hi".to_string()));
part.set_name(Some("Flute".to_string()));
part.insert(0.0, Note::from_name("C4")?);

let empty = part.clone_empty();
assert_eq!(empty.kind(), StreamKind::Part);
assert_eq!(empty.id(), Some("hi"));
assert_eq!(empty.name(), Some("Flute"));
assert!(empty.is_empty());
Source§

impl Stream

Source

pub fn element_at_or_before( &self, offset: FloatType, classes: &[&str], ) -> Option<&StreamEvent>

The element this stream holds itself that starts at offset, or nearest before it, of one of classes (any where none are named): music21’s getElementAtOrBefore. Of several starting at the same place, the last in the stream’s order.

music21 also looks among a stream’s elements stored at its end, which is where it keeps a measure’s right barline; the crate keeps barlines beside the elements (Stream::right_barline), so they are not found here.

use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("4/4 c4 d4 e2")?.flatten();
let found = line.element_at_or_before(1.5, &["Note"]).unwrap();
assert_eq!(found.offset(), 1.0);
Source

pub fn element_before_offset( &self, offset: FloatType, classes: &[&str], ) -> Option<&StreamEvent>

The element nearest before offset, not at it: music21’s getElementBeforeOffset. As Stream::element_at_or_before otherwise.

Source

pub fn element_after( &self, index: usize, classes: &[&str], ) -> Result<Option<&StreamEvent>>

The element after the one at index among this stream’s own, of one of classes (any where none are named): music21’s getElementAfterElement.

§Errors

An index this stream has no element at.

Source

pub fn beat_and_measure_from_offset( &self, offset: FloatType, fix_zeros: bool, ) -> Result<(FloatType, &Stream)>

Which beat of which measure offset falls on: music21’s beatAndMeasureFromOffset. The beat counts from one, as a proportion of the time signature in force at the measure.

A measure with a number suffix, or numbered nought where fix_zeros, is taken as the second half of the measure before it, which is answered instead, with the beat counted on from that measure’s last; a measure so numbered that opens the piece is taken as a pickup, its beats counted from the end of a full bar. A score answers for its first part with measures.

use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("3/4 c4 d4 e4 f2.")?;
let (beat, measure) = line.beat_and_measure_from_offset(4.0, true)?;
assert_eq!((beat, measure.number()), (2.0, 2));
§Errors

A stream with no measures, or none in any part; no measure at or before offset; no time signature in force there; or an offset past the bar it falls in.

Source

pub fn time_signatures( &self, return_default: bool, ) -> Result<Vec<(FloatType, TimeSignature)>>

The time signatures this stream holds, however deep, each where it stands from the stream’s start: music21’s getTimeSignatures. With return_default, 4/4 is put first at nought where none stands there.

music21 also looks outside a stream holding none, through the streams that hold it; a crate stream knows nothing outside itself.

§Errors

None in practice: the default 4/4 is always made.

Source

pub fn instruments( &self, recurse: bool, return_default: bool, ) -> Vec<Instrument>

The instruments this stream holds, however deep where recurse, in order: music21’s getInstruments. With return_default, an instrument with an empty part name stands for none found.

music21 also asks the stream holding this one where it holds none; a crate stream knows nothing outside itself.

Source

pub fn instrument( &self, recurse: bool, return_default: bool, ) -> Option<Instrument>

The first instrument this stream holds itself, or with recurse however deep: music21’s getInstrument. With return_default, an instrument with an empty part name where none is.

Source§

impl Stream

Source

pub fn lyrics( &self, options: &LyricsOptions, ) -> BTreeMap<IntegerType, Vec<SungLyric>>

The lyrics sung in this stream, gathered by the number each is sung under: music21’s lyrics.

Each number’s line has one place for every note read, holding the lyric sung there or SungLyric::Unsung where that note sings nothing under that number, so the lines stay level with the notes. A number first met partway through is padded with the notes before it, as music21 pads it.

use music21_rs::stream::{LyricsOptions, SungLyric};
use music21_rs::notation::Lyric;
use music21_rs::{Note, Stream};

let mut line = Stream::new();
for (name, word) in [("C4", "this"), ("D4", "is"), ("E4", "sung")] {
    let mut note = Note::from_name(name)?;
    note.lyrics_mut().push(Lyric::new(word));
    line.push(note);
}

let sung = line.lyrics(&LyricsOptions::default());
let words: Vec<String> = sung[&1]
    .iter()
    .map(|sung| match sung {
        SungLyric::Lyric(lyric) => lyric.text(),
        _ => String::new(),
    })
    .collect();
assert_eq!(words, ["this", "is", "sung"]);
Source

pub fn lyric_positions( &self, options: &LyricsOptions, ) -> BTreeMap<IntegerType, Vec<SungAt>>

Stream::lyrics in positions: each line with, for every note read, where the lyric sung there stands.

music21 hands back the Lyric objects the notes carry, so a caller keeping an object per element – a binding keeping what it read the stream from – answers with the note’s own lyric by looking it up at that position among Stream::leaves.

Source§

impl Stream

Source

pub fn scores(&self) -> Vec<&Stream>

The scores this opus holds: music21’s Opus.scores.

Source

pub fn score_numbers(&self) -> Vec<Option<String>>

Each score’s number, as its metadata gives it: music21’s Opus.getNumbers. A score whose metadata says nothing has none, where music21 raises on metadata it does not have.

Source

pub fn score_by_number(&self, query: &MetadataQuery<'_>) -> Option<&Stream>

The first score whose number a query matches: music21’s Opus.getScoreByNumber.

use music21_rs::metadata::{Metadata, MetadataQuery};
use music21_rs::{Stream, StreamKind};

let mut opus = Stream::with_kind(StreamKind::Opus);
for number in ["1", "2"] {
    let mut score = Stream::with_kind(StreamKind::Score);
    let mut metadata = Metadata::new();
    metadata.add_text("number", number);
    metadata.add_text("title", format!("Tune {number}"));
    score.set_metadata(Some(metadata));
    opus.push(score);
}

let second = opus.score_by_number(&MetadataQuery::Text("2")).unwrap();
assert_eq!(second.metadata().unwrap().title().as_deref(), Some("Tune 2"));
Source

pub fn score_by_title(&self, query: &MetadataQuery<'_>) -> Option<&Stream>

The first score whose title a query matches: music21’s Opus.getScoreByTitle. music21 reads a regular expression out of a title query that holds one; here that is a MetadataQuery::Matcher the caller builds.

Source

pub fn merge_scores(&self) -> Result<Stream>

One score of the opus’s scores laid out as its parts: music21’s Opus.mergeScores, for a collection whose scores are each one part of the same work.

Each score’s first part is written out as notation and inserted at the start of the new score, which takes the first title and the first composer any of them names.

§Errors

A score holding no part, which music21 raises on as well, or a part that cannot be written as notation.

Source§

impl Stream

Source

pub fn placed(&self) -> Vec<Placed<'_>>

Every element that is not itself a stream, in Stream::leaves order, each with where it stands and what is in force there.

A mark is in force from its offset on, the last one at or before an element winning. In a stream holding parts, each part reads its own marks and those the stream holds directly, never another part’s, which is music21’s getContextByClass for music written once.

use music21_rs::{KeySignature, Note, Stream, StreamElement, stream::StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
part.insert(0.0, KeySignature::new(-1));
part.insert(0.0, Note::from_name("B-4")?);
let placed = part.placed();
let note = placed
    .iter()
    .find(|placed| matches!(placed.element(), StreamElement::Note(_)))
    .unwrap();
assert_eq!(note.key_signature().and_then(KeySignature::sharps), Some(-1));
Source§

impl Stream

Source

pub fn highest_offset(&self) -> FloatType

Where the last element this stream holds itself starts, nought for an empty stream: music21’s highestOffset.

Source

pub fn lowest_offset(&self) -> FloatType

Where the first element this stream holds itself starts, nought for an empty stream: music21’s lowestOffset.

Source

pub fn has_measures(&self) -> bool

Whether this stream holds a measure itself: music21’s hasMeasures.

Source

pub fn has_voices(&self) -> bool

Whether this stream holds a voice itself: music21’s hasVoices.

Source

pub fn is_well_formed_notation(&self) -> bool

Whether the stream is notation as music21 writes it out: a measure or a voice; a part of measures; a score or other stream of parts, or an opus of scores, whose every stream holds measures; and nothing holding notes or rests loose: music21’s isWellFormedNotation.

Source

pub fn find_gaps(&self) -> Option<Stream>

The stretches of this stream, between its own elements, where nothing sounds, each as a rest, or nothing where there are none: music21’s findGaps.

use music21_rs::{Duration, Note, Stream};

let mut line = Stream::new();
line.insert(0.0, Note::from_name("C4")?.with_duration(Duration::quarter()));
line.insert(2.0, Note::from_name("D4")?.with_duration(Duration::quarter()));
let gaps = line.find_gaps().expect("a gap");
assert_eq!(gaps.events()[0].offset(), 1.0);
assert_eq!(gaps.events()[0].element().quarter_length(), 1.0);
assert!(!line.is_gapless());
Source

pub fn is_gapless(&self) -> bool

Whether this stream has no gaps: music21’s isGapless.

Source

pub fn overlaps(&self) -> Vec<(FloatType, Vec<StreamEvent>)>

The elements of the flattened stream that sound over one another, gathered by the offset where each overlapping group starts: music21’s getOverlaps. Only elements found overlapping looking on from one until the first that does not are gathered, as music21 gathers them.

use music21_rs::{Duration, Note, Stream};

let mut line = Stream::new();
line.insert(0.0, Note::from_name("C4")?.with_duration(Duration::half()));
line.insert(1.0, Note::from_name("E4")?.with_duration(Duration::quarter()));
line.insert(3.0, Note::from_name("G4")?.with_duration(Duration::quarter()));
let overlaps = line.overlaps();
assert_eq!(overlaps.len(), 1);
assert_eq!(overlaps[0].0, 0.0);
assert_eq!(overlaps[0].1.len(), 2);
assert!(!line.is_sequence());
Source

pub fn overlap_positions(&self) -> Vec<(FloatType, Vec<usize>)>

Stream::overlaps, each group’s members by their position among Stream::leaves rather than as values.

music21 hands back the elements themselves, so a caller keeping an object per element – a binding keeping what it read the stream from – finds each again by that position.

use music21_rs::{Duration, Note, Stream, StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
let mut measure = Stream::with_kind(StreamKind::Measure);
measure.insert(0.0, Note::from_name("C4")?.with_duration(Duration::half()));
measure.insert(1.0, Note::from_name("E4")?);
part.insert(0.0, measure);

// The two notes overlap, and are the part's first two leaves. The
// one overlapped is listed before the one looking on from itself,
// which is the order music21's own dictionary takes them in.
let found = part.overlap_positions();
assert_eq!(found.len(), 1);
assert_eq!(found[0], (0.0, vec![1, 0]));
Source

pub fn is_sequence(&self) -> bool

Whether no element of the flattened stream overlaps another, as Stream::overlaps finds them: music21’s isSequence.

Source

pub fn simultaneous_attacks(&self, other: &Stream) -> Vec<FloatType> ⓘ

The offsets where something in this stream and something in other both start, each stream’s own elements: music21’s simultaneousAttacks.

Source

pub fn playing_when_attacked( &self, element: &StreamElement, offset: FloatType, ) -> Option<&StreamEvent>

The element of this stream sounding where element starts, at offset: the one there, or of those there the first of element’s class, or else the first; nothing where none is: music21’s playingWhenAttacked.

Source

pub fn all_playing_while_sounding( &self, element: &StreamElement, offset: FloatType, ) -> Stream

Every element of this stream sounding while element, at offset, sounds, each at its offset from offset: music21’s allPlayingWhileSounding.

Source

pub fn offset_map(&self) -> Vec<OffsetMapEntry>

Each element of this stream with where it starts and ends, those of its voices flattened and labelled with the voice, barlines left out: music21’s offsetMap.

Source

pub fn measure_offset_map(&self) -> Vec<(FloatType, Vec<&Stream>)>

The measures by offset, in order: a score’s those of every part at each offset, and another stream’s its own: music21’s measureOffsetMap.

Source§

impl Stream

Source

pub fn expand_repeats(&self) -> Result<Stream>

This stream with its repeats played out, as music21’s expandRepeats plays them: every passage between repeat barlines written out as many times as its end says (twice where it says nothing), each first and second ending in its turn, and a da capo or dal segno jump taken – to the fine or through the coda where it says so.

A score has each part played out and keeps everything else it holds; a part keeps what stands outside its measures where it stood. A measure written out again is numbered as it was, with a, b and on after its number the second time and later; one played after a jump is renumbered on from the first. The repeat barlines become double ones and the jumps and markers are taken out. A spanner joins what it joined the first time through. A part with no repeats comes back as it is.

use music21_rs::bar::{Barline, RepeatDirection};
use music21_rs::{Note, Stream, StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
for (index, name) in ["C4", "D4"].into_iter().enumerate() {
    let mut measure = Stream::with_kind(StreamKind::Measure);
    measure.set_number(index as i32 + 1);
    measure.push(Note::from_name(name)?.with_duration(music21_rs::Duration::whole()));
    if index == 0 {
        measure.set_right_barline(Some(Barline::repeat(RepeatDirection::End, None)));
    }
    part.insert(index as f64 * 4.0, measure);
}
let played = part.expand_repeats()?;
let numbers: Vec<String> = played
    .measures()
    .iter()
    .map(|measure| measure.number_with_suffix())
    .collect();
assert_eq!(numbers, ["1", "1a", "2"]);
§Errors

A stream holding no measures, and repeats music21 cannot make sense of: barlines that do not pair up, endings that are not numbered one on from another or not closed by a repeat, and more than one jump.

Source§

impl Stream

Source

pub fn metronome_mark_boundaries( &self, ) -> Result<Vec<(FloatType, FloatType, MetronomeMark)>>

The stretches of the stream each tempo holds, start, end and the mark sounding there: music21’s metronomeMarkBoundaries.

The stream is read flattened, so a tempo written on a part is found from the score. Where it states no tempo, or none from its start, a quarter at 120 holds.

§Errors

A metric modulation whose new tempo cannot be worked out.

Source

pub fn metronome_mark_positions(&self) -> Result<Vec<TempoSpan>>

Stream::metronome_mark_boundaries, each stretch also saying which element the tempo was read off, by its position among Stream::leaves.

music21 hands back the mark objects the stream holds, so a caller keeping something of its own beside each element – a binding keeping the object it was handed – finds the mark again by that position. A stretch standing under no mark of the stream’s carries none: the quarter at 120 standing in for a stream that states no tempo, and the mark a tempo word or a metric modulation means, which music21 builds afresh as well.

§Errors

A metric modulation whose new tempo cannot be worked out.

Source

pub fn seconds(&self, in_force: Option<&MetronomeMark>) -> Result<FloatType>

How long the stream lasts in seconds: music21’s seconds.

Only the tempi the stream holds itself count, as music21’s do – a tempo inside a part of a score is not one of the score’s own – and each holds until the next, the last to the end of the stream. Where the stream states no tempo, or none from its start, in_force stands for what music21 searches its context for, and is read as a mark standing at nought, which is where music21 puts what it finds. What music21’s own search finds turns on sort order: a measure standing after a tempo in its part finds it, one standing at the same offset does not, a stream sorting before the marks at its offset.

With no tempo anywhere, a stream holding nothing that lasts is nought seconds long, and one holding something is NaN, which is what music21 answers rather than refusing.

use music21_rs::{Duration, MetronomeMark, Note, Stream, StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
part.insert(0.0, Note::from_name("C4")?.with_duration(Duration::whole()));
// A quarter at 60 makes the whole note four seconds.
assert_eq!(part.seconds(Some(&MetronomeMark::new(60.0)))?, 4.0);

// A tempo the stream holds itself is used from where it stands.
part.insert(0.0, MetronomeMark::new(120.0));
assert_eq!(part.seconds(None)?, 2.0);

// With no tempo at all, something that lasts answers NaN.
let mut bare = Stream::new();
assert_eq!(bare.seconds(None)?, 0.0);
bare.insert(0.0, Note::from_name("C4")?.with_duration(Duration::half()));
assert!(bare.seconds(None)?.is_nan());
§Errors

A tempo that says no number, or a metric modulation whose new tempo cannot be worked out.

Source§

impl Stream

Source

pub fn extract_context( &self, index: usize, before: FloatType, after: FloatType, ) -> Result<Stream>

A stream of the elements this stream holds itself that start from before quarters before the element at index to after quarters after it ends: music21’s extractContext. The stream keeps its kind and id; the elements keep their offsets, and spanners theirs.

use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("4/4 c4 d4 e4 f4 g4 a4")?.flatten();
let index = line.events().iter().position(|event| event.offset() == 2.0).unwrap();
let around = line.extract_context(index, 1.0, 1.0)?;
let offsets: Vec<f64> = around.notes().iter().map(|(offset, _)| *offset).collect();
assert_eq!(offsets, [1.0, 2.0, 3.0]);
§Errors

An index this stream holds no element at.

Source

pub fn remove_by_class(&mut self, classes: &[&str])

Takes out the elements this stream holds itself that are of one of classes, by music21’s class names: music21’s removeByClass. A spanner names nothing for an element taken out.

use music21_rs::tinynotation::from_tiny_notation;

let mut line = from_tiny_notation("4/4 c4 r4 e2")?.flatten();
line.remove_by_class(&["Rest", "TimeSignature"]);
assert!(line.events().iter().all(|event| !event.element().is_instance("Rest")));
assert_eq!(line.notes().len(), 2);
assert!(line.time_signatures(false)?.is_empty());
Source

pub fn remove_by_not_of_class(&mut self, classes: &[&str])

Takes out the elements this stream holds itself that are of none of classes: music21’s removeByNotOfClass.

Source§

impl Stream

Source

pub fn slice_by_quarter_lengths(&self, lengths: &[FloatType]) -> Result<Stream>

A copy of the stream with each note and rest cut into pieces of lengths, the list repeated as far as it takes to fill the note, tied: music21’s sliceByQuarterLengths. A note shorter than the list is left whole. A stream of measures is cut measure by measure, and a score part by part.

use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("4/4 c2 d4 e4")?;
let sliced = line.slice_by_quarter_lengths(&[1.0])?;
assert_eq!(sliced.notes().len(), 4);
§Errors

A note the list cannot add up to, which music21 refuses.

Source

pub fn slice_by_greatest_divisor(&self) -> Result<Stream>

A copy of the stream with each note and rest cut into pieces of the greatest length that goes into all of them, measure by measure: music21’s sliceByGreatestDivisor. A score finds one length for each measure across its parts.

Grace notes take no time to divide and are left whole; a measure with no notes or rests of its own is left as it is.

§Errors

Lengths with no common divisor music21’s approximateGCD finds; a score whose first part has more measures than another, or none of its own.

Source

pub fn slice_at_offsets(&self, offsets: &[FloatType]) -> Result<Stream>

A copy of the stream with each note and rest sounding across one of offsets cut there, tied: music21’s sliceAtOffsets. A stream of measures is cut measure by measure, each at the offsets that fall in it, and a score part by part. A note in a voice is cut in its voice, at the offsets counted from the voice’s start.

§Errors

A note that cannot be cut at a point.

Source

pub fn slice_by_beat(&self) -> Result<Stream>

A copy of the stream with each note and rest cut at the beats of its time signature: music21’s sliceByBeat. A stream of measures is cut measure by measure, each at the beats of the time signature in force there, and a score part by part. A stream with no time signature is cut at the beats of 4/4.

§Errors

A measure or stream holding more than one time signature, which music21 does not cut.

Source

pub fn split_by( &self, keep: impl Fn(&StreamElement) -> bool, ) -> (Stream, Stream)

The elements this stream holds itself in two streams of its kind: those keep accepts and the rest, at the offsets they stand at: music21’s splitByClass with no class.

Source§

impl Stream

Source

pub fn at_sounding_pitch(&self) -> Option<bool>

Whether this stream’s notes are written at the pitch they sound (Some(true)), at the pitch a transposing instrument reads (Some(false)), or nothing has said (None): music21’s atSoundingPitch, whose 'unknown' is None.

Setting it moves no notes; Stream::to_written_pitch and Stream::to_sounding_pitch do that. A stream that says nothing is read as the nearest stream holding it that does.

Source

pub fn set_at_sounding_pitch(&mut self, at_sounding_pitch: Option<bool>)

Says whether this stream’s notes are at sounding pitch.

Source

pub fn to_written_pitch(&self) -> Result<Stream>

This stream with its notes at the pitch each part’s instruments read them at: music21’s toWrittenPitch.

A part at sounding pitch is transposed by the reverse of each of its instruments’ transpositions – the notes, chords, chord symbols and key signatures from where the instrument stands to where the next one does – and then says it is at written pitch. A part already at written pitch, or one that says nothing and stands in nothing that does, is left as it is. A score or an opus is taken part by part, and then says it is at written pitch too.

use music21_rs::{Instrument, Note, Stream, StreamElement, StreamKind};

let mut part = Stream::with_kind(StreamKind::Part);
part.push(StreamElement::Instrument(Box::new(Instrument::of_kind(
    "Clarinet",
)?)));
part.push(StreamElement::Note(Note::from_name("Bb4")?));
part.set_at_sounding_pitch(Some(true));

let written = part.to_written_pitch()?;
let StreamElement::Note(note) = written.leaves()[1].1 else { unreachable!() };
assert_eq!(note.pitch().name_with_octave(), "C5");
assert_eq!(written.at_sounding_pitch(), Some(false));
Source

pub fn to_written_pitch_by(&self, ottavas_to_sounding: bool) -> Result<Stream>

Stream::to_written_pitch, given music21’s ottavasToSounding: whether the notes under an octave line are then put where they sound, as music21’s MusicXML writer has them, rather than where the line has them written.

Source

pub fn to_sounding_pitch(&self) -> Result<Stream>

This stream with its notes at the pitch they sound: music21’s toSoundingPitch, Stream::to_written_pitch the other way round. A part at written pitch is transposed by each of its instruments’ transpositions, and then says it is at sounding pitch; the notes under an octave line are put where they sound, and the line says so.

Source§

impl Stream

Source

pub fn elements_in_span(&self, span: &OffsetSpan) -> Vec<&StreamEvent>

The elements standing in a span of offsets: music21’s getElementsByOffset.

Everything starting after the span ends is out, and so is everything finishing before it starts. What touches an edge is decided by the span’s four flags, and a mark of no length standing anywhere in a span of no length is always taken.

An element is only found where it begins, because music21’s mustBeginInSpan starts true: a half note at nought is not found at the offset halfway through it, though it is still sounding there. Setting must_begin_in_span false is what reaches back to it, and is how music21 asks what sounds at a point.

Offsets are compared as music21 compares them, a snapped fraction against a float, so an element at a third of a quarter is found by the float that names it.

use music21_rs::stream::OffsetSpan;
use music21_rs::{Duration, Note, Stream, StreamKind};

let mut measure = Stream::with_kind(StreamKind::Measure);
measure.insert(0.0, Note::from_name("C4")?.with_duration(Duration::half()));
measure.insert(2.0, Note::from_name("E4")?.with_duration(Duration::half()));

// Nothing begins halfway through the first note.
assert!(measure.elements_in_span(&OffsetSpan::at(1.0)).is_empty());

// What sounds there is asked for by reaching back.
let mut sounding = OffsetSpan::at(1.0);
sounding.must_begin_in_span = false;
let found = measure.elements_in_span(&sounding);
assert_eq!(found.len(), 1);
assert_eq!(found[0].offset(), 0.0);

// A stretch takes what begins anywhere in it, its end included.
let found = measure.elements_in_span(&OffsetSpan::between(1.0, 2.0));
assert_eq!(found.len(), 1);
assert_eq!(found[0].offset(), 2.0);
Source

pub fn elements_of_class(&self, classes: &[&str]) -> Vec<&StreamEvent>

The elements answering to any of these music21 class names: music21’s getElementsByClass.

use music21_rs::{Note, Stream, StreamKind, TimeSignature};

let mut measure = Stream::with_kind(StreamKind::Measure);
measure.insert(0.0, TimeSignature::new(4, 4)?);
measure.insert(0.0, Note::from_name("C4")?);
assert_eq!(measure.elements_of_class(&["Note"]).len(), 1);
assert_eq!(measure.elements_of_class(&["GeneralNote"]).len(), 1);
assert!(measure.has_element_of_class(&["TimeSignature"]));
assert_eq!(measure.elements_not_of_class(&["Note"]).len(), 1);
Source

pub fn elements_not_of_class(&self, classes: &[&str]) -> Vec<&StreamEvent>

The elements answering to none of these music21 class names: music21’s getElementsNotOfClass.

Source

pub fn has_element_of_class(&self, classes: &[&str]) -> bool

Whether any element answers to one of these music21 class names: music21’s hasElementOfClass.

Source§

impl Stream

Source

pub fn in_force_before(&self, offset: FloatType) -> InForce

The clef, key and time signature in force before offset: the last of each this stream holds, however deep, standing before it.

Source

pub fn split_at_quarter_length( &self, quarter_length: FloatType, in_force: &InForce, ) -> Result<(Stream, Stream)>

The stream cut in two quarter_length into it: music21’s splitAtQuarterLength. What starts before the point and sounds past it is cut there, tied, its second piece starting the second half; what starts at or after the point moves to the second half, as far from its start. A voice is cut as a stream is.

The second half of a measure is a measure of its own holding the time signature of the first (or in_force’s where it has none), and the key and clef in force at the point: the first half’s own last before it, or in_force’s. Spanners stay with the first half, naming nothing for what moved.

use music21_rs::stream::InForce;
use music21_rs::tinynotation::from_tiny_notation;

let line = from_tiny_notation("4/4 c2 d2")?;
let measure = line.measures()[0].clone();
let (first, second) = measure.split_at_quarter_length(1.0, &InForce::default())?;
assert_eq!(first.notes().len(), 1);
assert_eq!(second.notes().len(), 2);
§Errors

An element that cannot be cut at the point.

Source§

impl Stream

Source

pub fn template(&self, options: &TemplateOptions) -> Stream

The stream and every stream inside it with what options says taken away, a rest standing in for each stretch of what went where asked: music21’s template. Each run of elements taken away between two kept is one rest, from where the first starts to where the longest of them ends. Spanners stay, naming nothing for what is gone, unless remove_all takes everything.

Source

pub fn insert_into_note_or_chord( &mut self, offset: FloatType, element: StreamElement, chords_only: bool, ) -> Result<()>

Adds a note or chord where something already starts within its length, merging the two into one chord: music21’s insertIntoNoteOrChord. Where a rest starts there it gives way to the note or chord; where nothing does, the note or chord is simply inserted. The merged chord, or the note or rest a merge of one pitch or none makes, keeps the length, articulations, expressions, lyrics, stem and notehead fill of what stood there; with chords_only, a merge of one pitch is still a chord. An unpitched note or percussion chord standing there takes no pitches in, and becomes a rest, as in music21.

§Errors

More than one note, chord or rest starting within the length, which music21 refuses; a chord symbol whose pitches cannot be read; or lyrics to carry onto a chord of no pitches.

Source

pub fn flatten_unnecessary_voices(&mut self, force: bool)

Takes away the voices holding nothing and, where one voice is left, puts what it holds back in the stream itself: music21’s flattenUnnecessaryVoices. With force, every voice left is flattened so.

Source§

impl Stream

Source

pub fn strip_ties(&mut self, match_by_pitch: bool) -> Result<()>

Folds every run of tied notes into its first note, lengthened by the rest of the run, which are taken out: music21’s stripTies.

A stream holding parts has each of them done, and one holding voices each voice. Otherwise every note, chord and rest is taken in one line in the order the stream flattens to, measures and voices alike, and a run of them is joined by its ties. With match_by_pitch a note joins the run before it only by sounding the pitch the last of it does – a chord, every pitch on the same letter and enharmonic – whatever its tie says; without, a chord joins one whose notes are all tied on and as many. The note kept is given the run’s length as a plain value and loses its tie; a spanner joined to a note taken out is joined to the note kept instead. Notes of no length, grace notes among them, are left as they are.

use music21_rs::notation::{Tie, TieType};
use music21_rs::{Duration, Note, Stream, StreamElement};

let mut stream = Stream::new();
let mut first = Note::from_name("C4")?.with_duration(Duration::half());
first.set_tie(Some(Tie::new(TieType::Start)));
let mut second = Note::from_name("C4")?;
second.set_tie(Some(Tie::new(TieType::Stop)));
stream.push(first);
stream.push(second);
stream.strip_ties(true)?;

let leaves = stream.leaves();
assert_eq!(leaves.len(), 1);
assert_eq!(leaves[0].1.quarter_length(), 3.0);
§Errors

A run whose notes after the first last no time at all, as music21 raises for one.

Source§

impl Stream

Source

pub fn voices_to_parts(&self, separate_by_id: bool) -> Result<Stream>

A score with a part for each voice of this part, as music21’s voicesToParts makes it; a score has each of its parts so split.

Each measure holding voices gives each part a measure of its own, with the measure’s barlines, meters, clefs and keys and one voice’s music; parts with no voice in that measure get the settings alone. A measure without voices goes whole to the first part, and the others get its barlines, meters and keys. Every part has the original’s instruments, and its first measure the clef that best fits its notes (Clef::best_for). The parts are numbered by voice, -v0 after the part’s id and so on, or with separate_by_id, named after the voices’ ids, each voice going to the part of its id whatever its place in the measure.

use music21_rs::{Note, Stream, StreamKind};

let mut upper = Stream::with_kind(StreamKind::Voice);
upper.insert(0.0, Note::from_name("E5")?);
let mut lower = Stream::with_kind(StreamKind::Voice);
lower.insert(0.0, Note::from_name("C3")?);
let mut measure = Stream::with_kind(StreamKind::Measure);
measure.insert(0.0, upper);
measure.insert(0.0, lower);
let mut part = Stream::with_kind(StreamKind::Part);
part.set_id(Some("P1".to_string()));
part.insert(0.0, measure);

let score = part.voices_to_parts(false)?;
let parts = score.parts();
assert_eq!(parts.len(), 2);
assert_eq!(parts[1].id(), Some("P1-v1"));
assert_eq!(parts[1].pitches()[0].name_with_octave(), "C3");
§Errors

With separate_by_id, a part with measures none of which hold a voice, which music21 gives no part to put its music in.

Source

pub fn explode(&self) -> Result<Stream>

A score with a part for each voice: music21’s explode, which is Stream::voices_to_parts by place.

§Errors

As Stream::voices_to_parts.

Source

pub fn parts_to_voices( &self, allocation: &VoiceAllocation, permit_one_voice_per_part: bool, set_stems: bool, ) -> Result<Stream>

A score whose parts each hold several of this score’s parts as voices, as music21’s partsToVoices makes it.

The parts are grouped by allocation. A group of one part is kept as it is unless permit_one_voice_per_part. Otherwise each measure of the new part has the first part’s measure’s number, barlines, meters, clefs and keys, and a voice for each part of the group, numbered from nought, holding the notes, chords and rests that measure holds itself – not those in its own voices. With set_stems, the notes of the first, third … voice have their stems up and the others down. The parts’ spanners come along; the score keeps its metadata and nothing else.

use music21_rs::{Note, Stream, StreamKind};
use music21_rs::stream::VoiceAllocation;

let mut score = Stream::with_kind(StreamKind::Score);
for name in ["E5", "C3"] {
    let mut measure = Stream::with_kind(StreamKind::Measure);
    measure.insert(0.0, Note::from_name(name)?);
    let mut part = Stream::with_kind(StreamKind::Part);
    part.insert(0.0, measure);
    score.insert(0.0, part);
}
let joined = score.parts_to_voices(&VoiceAllocation::Each(2), false, true)?;
assert_eq!(joined.parts().len(), 1);
assert_eq!(joined.parts()[0].measures()[0].voices().len(), 2);
§Errors

A group naming a part the score has not got, or a later part of a group with more measures than the first.

Source

pub fn implode(&self) -> Result<Stream>

Parts joined two to a part as voices: music21’s implode, which is Stream::parts_to_voices with its defaults.

§Errors

As Stream::parts_to_voices.

Source§

impl Stream

Source

pub fn new() -> Self

Creates an empty stream.

Source

pub fn with_kind(kind: StreamKind) -> Self

Creates an empty stream standing for one of music21’s subclasses.

Source

pub fn number(&self) -> IntegerType

A measure’s number: music21’s Measure.number, which is nought until something numbers it.

Source

pub fn set_number(&mut self, number: IntegerType)

Numbers the measure.

Source

pub fn number_suffix(&self) -> Option<&str>

What follows the number, as the a of a measure numbered 12a: music21’s numberSuffix.

Source

pub fn set_number_suffix(&mut self, suffix: Option<String>)

Sets what follows the number, or clears it.

Source

pub fn number_with_suffix(&self) -> String

The number with its suffix, 12a: music21’s measureNumberWithSuffix.

Source

pub fn number_hidden(&self) -> bool

Whether the measure’s number is left unshown, as a pickup bar’s is: music21’s showNumber set to NEVER.

Source

pub fn set_number_hidden(&mut self, hidden: bool)

Says whether the measure’s number is left unshown.

Source

pub fn measure_numbering(&self) -> Option<&str>

Which measures’ numbers are shown from this measure on, as MusicXML’s <measure-numbering> says it – none, measure or system: music21’s style.measureNumbering. How the numbers are drawn is not kept.

Source

pub fn set_measure_numbering(&mut self, numbering: Option<String>)

Says which measures’ numbers are shown from this measure on.

Source

pub fn id(&self) -> Option<&str>

The name the stream is known by, as a part’s P1: music21’s id where one was given rather than taken from a memory address.

Source

pub fn set_id(&mut self, id: Option<String>)

Sets the stream’s id, or clears it.

Source

pub fn name(&self) -> Option<&str>

A part’s name, as printed beside its first system: music21’s partName.

Source

pub fn set_name(&mut self, name: Option<String>)

Names the part, or clears the name.

Source

pub fn abbreviation(&self) -> Option<&str>

A part’s short name, as printed beside the systems after the first: music21’s partAbbreviation.

Source

pub fn set_abbreviation(&mut self, abbreviation: Option<String>)

Sets the part’s short name, or clears it.

Source

pub fn name_hidden(&self) -> bool

Whether the part’s name is left unprinted: music21’s style.printPartName set to false.

Source

pub fn set_name_hidden(&mut self, hidden: bool)

Says whether the part’s name is left unprinted.

Source

pub fn abbreviation_hidden(&self) -> bool

Whether the part’s short name is left unprinted: music21’s style.printPartAbbreviation set to false.

Source

pub fn set_abbreviation_hidden(&mut self, hidden: bool)

Says whether the part’s short name is left unprinted.

Source

pub fn metadata(&self) -> Option<&Metadata>

The title, composer and the rest a score carries: music21’s metadata.

Source

pub fn set_metadata(&mut self, metadata: Option<Metadata>)

Sets the metadata, or clears it.

Source

pub fn staff_groups(&self) -> &[StaffGroup]

The groups a score brackets its parts in, in the order they were added.

Source

pub fn add_staff_group(&mut self, group: StaffGroup)

Brackets some of the score’s parts together.

Source

pub fn left_barline(&self) -> Option<&Barline>

The barline a measure starts with, where it is not an ordinary one: music21’s leftBarline.

Source

pub fn set_left_barline(&mut self, barline: Option<Barline>)

Sets the barline a measure starts with, or clears it.

Source

pub fn right_barline(&self) -> Option<&Barline>

The barline a measure ends with, where it is not an ordinary one: music21’s rightBarline.

Source

pub fn set_right_barline(&mut self, barline: Option<Barline>)

Sets the barline a measure ends with, or clears it.

Source

pub fn padding_left(&self) -> FloatType

How much of a measure’s bar goes unfilled before its first note, as a pickup leaves the start of its bar: music21’s paddingLeft.

Source

pub fn set_padding_left(&mut self, padding: FloatType)

Says how much of the bar goes unfilled before the first note.

Source

pub fn padding_right(&self) -> FloatType

How much of a measure’s bar goes unfilled after its last note, as a measure cut short leaves its end: music21’s paddingRight.

Source

pub fn set_padding_right(&mut self, padding: FloatType)

Says how much of the bar goes unfilled after the last note.

Source

pub fn ending(&self) -> Option<&Ending>

The alternative ending a measure is part of, where it is in one.

Source

pub fn set_ending(&mut self, ending: Option<Ending>)

Puts the measure in an alternative ending, or takes it out.

Source

pub fn spanners(&self) -> &[Spanner]

The slurs and other spanners this stream holds, each naming what it joins by position in this stream’s Stream::leaves.

Source

pub fn add_spanner(&mut self, spanner: Spanner)

Adds a spanner, naming what it joins by position in this stream’s Stream::leaves.

Source

pub fn kind(&self) -> StreamKind

Which of music21’s Stream subclasses this stands for.

Source

pub fn set_kind(&mut self, kind: StreamKind)

Sets which subclass this stands for.

Source

pub fn from_events(events: impl IntoIterator<Item = StreamEvent>) -> Self

Creates a stream from events, sorted by offset.

Source

pub fn insert(&mut self, offset: FloatType, element: impl Into<StreamElement>)

Inserts an element at a quarter-length offset.

Source

pub fn push(&mut self, element: impl Into<StreamElement>)

Appends an element after the current end of the stream.

Source

pub fn events_mut(&mut self) -> &mut [StreamEvent]

Returns immutable events in offset order.

Source

pub fn events(&self) -> &[StreamEvent]

The events in offset order.

Source

pub fn iter(&self) -> impl Iterator<Item = &StreamEvent>

Iterates over events in offset order.

Source

pub fn len(&self) -> usize

How many events this stream holds directly, not counting what any nested stream holds.

Source

pub fn is_empty(&self) -> bool

Whether this stream holds nothing at all.

Source

pub fn flatten(&self) -> Self

One timeline with the nesting dissolved: music21’s flatten.

Each nested stream’s offset is added to its contents’, and the streams themselves are gone; everything else comes through in music21’s order: by offset, then at one offset by class – a clef before a key before a dynamic before a chord symbol before a note – with grace notes first among their class, and otherwise as the nesting held them, part by part.

Source

pub fn recurse(&self) -> Vec<(FloatType, &StreamElement)>

Every element at its offset from this stream’s start, nested streams themselves included: music21’s recurse.

Source

pub fn leaves(&self) -> Vec<(FloatType, &StreamElement)>

Every element that is not itself a stream, at its offset from this stream’s start, in the order Stream::for_each_mut hands them over.

An element’s index in this list is its position, which is how the walks answering about particular elements say which they mean: crate::volume::dynamics_in_force, crate::chordsymbol::chord_symbol_durations, crate::voiceleading::voice_leading_quartet_positions and crate::voiceleading::verticality_positions_at. A caller keeping something of its own beside each element, as a binding keeps the object it was handed, finds it again by the same index.

Source

pub fn remove_event(&mut self, index: usize) -> Option<StreamEvent>

Takes out one of this stream’s own events, and with it whatever it holds: music21’s remove. Every spanner, here or in a nested stream, is moved to where what it names now stands, and names nothing for an element taken out. Nothing is taken out for a place past the end.

Source

pub fn for_each_mut( &mut self, visit: &mut impl FnMut(FloatType, &mut StreamElement), )

Hands every element to a closure with its offset from this stream’s start, nested streams’ contents included, so that it may be changed where it sits.

Stream::flatten and Stream::recurse hand back copies and references; this is the walk for an edit that has to land in the score itself. Things at one offset come in the same order flatten gives them. A nested stream is walked into rather than handed over.

Source

pub fn retain_leaves( &mut self, keep: &mut impl FnMut(usize, &mut StreamElement) -> bool, )

Keeps the leaves keep accepts, handed each with its position in Stream::leaves to change as it likes, and drops the rest. Every spanner, here or in a nested stream, is moved to where what it names now stands, and names nothing for an element dropped.

Source

pub fn has_part_like_streams(&self) -> bool

Whether this stream holds parts, or streams standing in for them: music21’s hasPartLikeStreams. A part says so; a measure or a voice, or a stream starting anywhere but the beginning, says not; any other stream holding measures or notes and rests says so, unless a later one says not.

Source

pub fn streams_of_kind(&self, kind: StreamKind) -> Vec<&Stream>

The streams of one kind held directly by this one: music21’s .parts on a score, .measures on a part, .voices on a measure.

Source

pub fn parts(&self) -> Vec<&Stream>

The parts this stream holds, a staff of a part written on several included: music21’s .parts, which a PartStaff is one of.

Source

pub fn measures(&self) -> Vec<&Stream>

The measures this stream holds.

Source

pub fn voices(&self) -> Vec<&Stream>

The voices this stream holds.

Source

pub fn notes(&self) -> Vec<(FloatType, StreamElement)>

Every note and chord on the flattened timeline: music21’s flatten().notes, which leaves rests out.

Source

pub fn end_offset(&self) -> FloatType

Returns the maximum event end offset, a nested stream’s own length included, snapped to the fraction it stands for: music21’s highestTime.

Source

pub fn pitches(&self) -> Vec<Pitch>

Returns all pitches in timeline order, from nested streams too.

Source

pub fn key_signature_at(&self, offset: FloatType) -> Option<KeySignature>

The key signature in force at an offset: the last one written at or before it, anywhere in the nesting.

This is what music21 answers with getContextByClass(KeySignature), found by looking back along the flattened timeline rather than by walking the sites an object belongs to.

Source

pub fn time_signature_at(&self, offset: FloatType) -> Option<TimeSignature>

The metre in force at an offset, found the same way.

Source

pub fn metronome_mark_at(&self, offset: FloatType) -> Option<MetronomeMark>

The tempo in force at an offset, found the same way.

Source

pub fn transpose(&self, interval: &Interval) -> Result<Self>

Returns a transposed copy, nesting and all.

Source§

impl Stream

Source

pub fn activate_variants( &self, group: Option<&str>, match_by_span: bool, ) -> Result<Stream>

A copy of the stream with its variants of group (or all of them) made its reading, as music21’s activateVariants makes them: what each replaces goes into a variant of group default in its place, a longer or shorter one moving what follows, and the measures are numbered again. With match_by_span, a variant replaces everything of its classes within its span; without, each of its elements the first of its class where it starts.

use music21_rs::tinynotation::from_tiny_notation;
use music21_rs::variant::merge_variants;

let first = from_tiny_notation("4/4 c1 d1 e1")?;
let second = from_tiny_notation("4/4 c1 f1 e1")?;
let merged = merge_variants(&first, &second, "second")?;
let made = merged.activate_variants(Some("second"), true)?;
assert_eq!(made.pitches()[1].name(), "F");
§Errors

A variant that cannot say what it replaces, or measures put in after none to be numbered from, where music21 fails.

Source

pub fn show_variant_as_ossialike_part( &self, part: usize, variant_groups: &[&str], ) -> Result<Stream>

A copy of a score with, for each of variant_groups whose variants replace something in the part at part among its parts, a part added showing only those variants: the part’s notes and rests made hidden rests and its variants of that group made its reading, as music21’s showVariantAsOssialikePart does.

§Errors

No part at part, or as Stream::activate_variants.

Trait Implementations§

Source§

impl Clone for Stream

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Stream

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Stream

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Stream

Available on crate feature serde only.
Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<Stream> for StreamElement

Source§

fn from(value: Stream) -> Self

Converts to this type from the input type.
Source§

impl<'a> IntoIterator for &'a Stream

Source§

type Item = &'a StreamEvent

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, StreamEvent>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl Serialize for Stream

Available on crate feature serde only.
Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.