alto.audio
Note playback: recorded instrument samples (University of Iowa), with pitch-shifting for missing notes.
Sounds plays notes through Qt’s QSoundEffect, one effect per note, created the first time it is needed. A note with
no recording is made by shifting the nearest recording (or, for the piano outside its sampled range, by synthesis).
Instrument previews render the phrase as one cached clip, with fixed spacing between its notes.
The module-level sounds is the one the interface uses.
Examples
>>> [inst.label for inst in INSTRUMENTS][:2]
['Piano', 'Flute']
>>> Sounds().instrument
'piano'
synth_piano
def synth_piano(
midi: int,
*,
duration: float = 1.6,
) -> np.ndarray
Synthesize a piano note, for notes outside the recorded range.
An additive model: stretched partials, a decay for each partial, a detuned string pair, and a hammer thump.
Parameters
midi(int): The MIDI note number. The same number always gives the same sound.duration(float, default 1.6): How long the note lasts, in seconds. Keyword-only.
Returns
- numpy.ndarray: Mono samples at
SAMPLE_RATE, scaled so the loudest is 0.8.
Examples
>>> samples = synth_piano(60, duration=0.1)
>>> len(samples)
4410
>>> round(float(np.max(np.abs(samples))), 1)
0.8
Instrument
Instrument(
key: str,
*,
label: str,
folder: str,
gain: float = 1.0,
sustained: bool = False,
family: str = '',
variant: str = '',
damped: bool = False,
)
An instrument that notes can be played on, and where its recordings are.
Attributes
key(str): A short identifier used in settings and file names.label(str): The name shown in the interface. Keyword-only.folder(str): Underassets/: “piano” or “samples/". File names are MIDI note numbers. Keyword-only. gain(float, default 1.0): The level relative to the piano. Keyword-only.sustained(bool, default False): True for bowed and blown instruments, whose notes end when the next one begins; struck and plucked ones ring on. Keyword-only.damped(bool, default False): True for an instrument whose notes are stopped by a damper when the key is let go, played without the pedal: the piano. Each note ends as the next one begins, as it does when the fingers move from key to key, instead of ringing on over the following notes as if the pedal were down. Keyword-only.family(str, default ““): Instruments that are ways of playing the same instrument share a family (the viola: arco and pizzicato). Keyword-only.variant(str, default ““): Which way of playing it, within the family. Keyword-only.
Examples
>>> Instrument("flute", label="Flute", folder="samples/flute", sustained=True).gain
1.0
>>> INSTRUMENT_BY_KEY["piano"].damped, INSTRUMENT_BY_KEY["marimba"].damped
(True, False)
Instrument.playback_volume
def playback_volume(level: float = 1.0) -> float
Return the output volume for a note or clip played on this instrument.
Parameters
level(float, default 1.0): Relative amplitude. Simultaneous notes can request a lower level for each voice.
Returns
- float: Linear Qt volume between zero and one, including the instrument’s gain.
Examples
>>> INSTRUMENT_BY_KEY["flute"].playback_volume()
0.85
instrument_groups
def instrument_groups() -> list[tuple[str, list[Instrument]]]
Return the instruments as they are listed for choosing.
Ways of playing one instrument share a single entry.
Returns
- list of tuple of (str, list of Instrument): Each entry’s name (the family, or the instrument’s own label) and its instruments, in the order listed.
Examples
>>> [name for name, _ in instrument_groups()]
['Piano', 'Flute', 'French Horn', 'Viola', 'Marimba', 'Vibraphone']
>>> [inst_.variant for inst_ in dict(instrument_groups())["Viola"]]
['Arco', 'Pizzicato']
read_wav
def read_wav(path: Path) -> tuple[np.ndarray, int]
Read a mono 16-bit WAV file.
Parameters
path(Path): The file.
Returns
- tuple of (numpy.ndarray, int): The samples as floats from -1 to 1, and the sample rate in hertz.
Examples
>>> import tempfile
>>> path_ = Path(tempfile.mkdtemp()) / "silence.wav"
>>> _ = path_.write_bytes(to_wav_bytes(np.zeros(10)))
>>> samples, rate = read_wav(path_)
>>> len(samples), rate
(10, 44100)
shift_pitch
def shift_pitch(
samples: np.ndarray,
*,
semitones: float,
) -> np.ndarray
Change the pitch of samples by resampling them.
It also changes the length, which is fine for a few semitones.
Parameters
samples(numpy.ndarray): Mono samples.semitones(float): How far to shift; positive is higher. Keyword-only.
Returns
- numpy.ndarray: The resampled samples, shorter when shifted up and longer when shifted down.
Examples
>>> len(shift_pitch(np.zeros(100), semitones=12)) # an octave up: half as long
50
to_wav_bytes
def to_wav_bytes(
samples: np.ndarray,
*,
rate: int = SAMPLE_RATE,
) -> bytes
Encode samples as a mono 16-bit WAV file in memory.
Parameters
samples(numpy.ndarray): Mono samples from -1 to 1.rate(int, default SAMPLE_RATE): The sample rate in hertz. Keyword-only.
Returns
- bytes: The contents of a WAV file.
Examples
>>> to_wav_bytes(np.zeros(10))[:4]
b'RIFF'
Sounds
Sounds()
A lazy cache of notes played through QSoundEffect, in the chosen instrument.
Attributes
enabled(bool): False while the app is muted.instrument(str): The key of the instrument in use, a key ofINSTRUMENT_BY_KEY.FADE_MS(int): How quickly a sustained note dies away when the next one begins, in milliseconds.
Examples
>>> s = Sounds()
>>> s.enabled, s.instrument
(True, 'piano')
>>> s.enabled = False # muted: nothing below makes a sound
>>> s.play_midi(60)
Constructor
Create a player with the piano chosen and sound on.
Constructor examples
>>> Sounds().instrument
'piano'
Sounds.recordings
def recordings(inst: Instrument) -> dict[int, Path]
Return the notes an instrument has a recording for on disk.
Parameters
inst(Instrument): The instrument.
Returns
- dict of int to Path: MIDI note number to its sample file.
Examples
>>> 60 in Sounds().recordings(INSTRUMENT_BY_KEY["piano"])
True
Sounds.play_midi
def play_midi(
midi: int,
*,
volume: float = 1.0,
instrument: str | None = None,
force: bool = False,
release_previous: bool = True,
) -> None
Play a note in the chosen instrument (or another one).
A sustained instrument (bowed or blown) ends the notes still sounding first, as a player would, and so does a damped
one (the piano, played without the pedal), unless release_previous is False, which is for the notes of a chord
that start together. Nothing plays while muted unless
force is set. A failure to play is reported but never raised, so audio can never break an exercise.
Parameters
midi(int): The MIDI note number.volume(float, default 1.0): The level from 0 to 1, before the instrument’s own gain. Keyword-only.instrument(str or None, default None): The key of the instrument to use instead of the chosen one. Keyword-only.force(bool, default False): Play even while muted, for previews. Keyword-only.release_previous(bool, default True): End the sustained or damped notes still ringing first. Keyword-only.
Examples
>>> s = Sounds()
>>> s.enabled = False
>>> s.play_midi(60) # muted: returns at once
>>> Sounds().play_midi(60) # doctest: +SKIP
Sounds.stop_all
def stop_all() -> None
Silence every note at once, and cancel any fade-outs underway.
Examples
>>> Sounds().stop_all()
Sounds.preview
def preview(
key: str,
*,
midis: Iterable[int],
step_ms: int = 300,
) -> None
Play notes one after another in an instrument, even while muted, to hear what it sounds like.
The phrase is rendered as one audio clip, so first-use loading cannot change the spacing between notes. Starting a preview silences the one before it.
Parameters
key(str): The key of the instrument.midis(iterable of int): The MIDI notes to play, in order. Keyword-only.step_ms(int, default 300): The time between notes, in milliseconds. Keyword-only.
Examples
>>> sounds.preview("flute", midis=[60, 64, 67]) # doctest: +SKIP
Sounds.play_notes
def play_notes(
columns: Iterable[Sequence[Note]],
*,
gap_ms: int = DEFAULT_NOTE_GAP_MS,
warmup: bool = False,
force: bool = False,
on_step: Callable[[int | None], object] | None = None,
) -> None
Play staff columns left to right, evenly spaced.
The notes within a column sound together, a little quieter the more there are.
Parameters
force(bool): Play even when exercise audio is muted.warmup(bool): Silently initialize audio streams before starting playback.columns(iterable of sequence of Note): The columns of notes, as drawn on a staff.gap_ms(int, default 450): The time between columns, in milliseconds. Keyword-only.on_step(callable or None, default None): Called with the index of each column as it starts, and with None when the last has had its time. It is called while muted too, so a display can follow the music with the sound off. Keyword-only.
Examples
>>> s = Sounds()
>>> s.enabled = False
>>> s.play_notes([[Note.parse("C4"), Note.parse("E4"), Note.parse("G4")]]) # muted: nothing sounds
Sounds.stop_sample
def stop_sample(on_step: Callable[[int | None], object]) -> None
Stop a displayed sample if it still owns playback.
Parameters
on_step(callable): The display callback originally passed to play_sample.
Examples
>>> Sounds().stop_sample(print)
Sounds.play_sample
def play_sample(
columns: Sequence[Sequence[Note]],
*,
gap_ms: int,
on_step: Callable[[int | None], object],
force: bool = False,
warmup: bool = False,
) -> None
Play a displayed sample and report the sounding column until it ends or is interrupted.
Parameters
columns(sequence of sequence of Note): Written notes in playback order, with simultaneous notes grouped together.gap_ms(int): Time between column onsets in milliseconds.on_step(callable): Receives each sounding column index and None to clear the display.force(bool): Audition the sample even when exercise audio is muted.warmup(bool): Prepare the audio streams before the first note.
Examples
>>> player = Sounds()
>>> player.enabled = False
>>> player.play_sample([[Note.parse("C4")]], gap_ms=300, on_step=print)
0
>>> player.stop_sample(print)
None
Sounds.play_melody
def play_melody(
midis: Iterable[int],
*,
gap_ms: int,
on_step: Callable[[int | None], object],
force: bool = False,
) -> None
Play a melody as one clip and synchronize highlights with processed audio frames.
Rendering fixes the note onsets even on first use, before samples have been loaded. Muted or unavailable audio still walks the visual steps. The last note sustains for an extra 200 ms. A newer playback cancels visual callbacks.
Parameters
midis(iterable of int): MIDI notes in playback order.gap_ms(int): Milliseconds between note onsets. Keyword-only.force(bool): Play even when exercise audio is muted.on_step(callable): Receives each sounding note’s index, then None after the last note’s time. Keyword-only.
Examples
>>> player = Sounds()
>>> player.enabled = False
>>> seen = []
>>> player.play_melody([60], gap_ms=300, on_step=seen.append)
>>> seen
[0]
Sounds.play_correct
def play_correct(streak: int) -> None
Play a note that climbs the C major scale (C5 to C6) as the streak grows, then wraps.
Parameters
streak(int): How many right answers in a row; 1 plays C5.
Examples
>>> s = Sounds()
>>> s.enabled = False
>>> s.play_correct(3) # muted: nothing sounds