Skip to content

xnano.audio

xnano.audio

xnano.audio

What is heard: Note, Melody, Audio and load_audio, play, and the Microphone. A canvas plays through its Speaker. Making a Note needs nothing; playing, melodies, audio and the microphone need the optional audio extra: pip install "xnano[audio]".

Classes:

  • Audio –

    Audio to play: a recording loaded from a file, samples you made, or what a canvas played.

  • Note –

    A note, or a chord, to play: a pitch, how long it lasts and how it sounds.

  • PlayHandle –

    What play returns: tells whether the sound is over and can cut it short.

  • Melody –

    Notes in order, written as text and parsed: 'C4 E4 G4:2 rest C5+E5+G5'.

  • Microphone –

    The canvas's microphone: how loud the sound at the default input device is.

Functions:

  • load_audio –

    Load audio from an audio file: its path, or its bytes.

  • play –

    Play a note, a sound, a symbol name, a melody or a sequence of those.

Attributes:

  • InstrumentName –

    The name of a built-in instrument, such as 'piano', 'bell' or 'kick'.

  • NoteName –

    A note name: a letter, an optional # or b, and an octave from 0 to 8, such as 'C4' or 'Bb3'.

  • Pitch –

    A pitch: a note name such as 'C#4' or a MIDI number from 0 to 127.

  • TerminalAudioError –

    Raised when a sound device or stream fails.

  • TerminalAudioUnavailableError –

    Raised when this computer has no sound device, or this build has no device support.

  • instrument_names –

    The name of every built-in instrument, in catalog order.

InstrumentName module-attribute

InstrumentName = _AudioInstrumentName

The name of a built-in instrument, such as 'piano', 'bell' or 'kick'.

Maps to xnano_audio.InstrumentName.

NoteName module-attribute

NoteName = _AudioNoteName

A note name: a letter, an optional # or b, and an octave from 0 to 8, such as 'C4' or 'Bb3'.

Maps to xnano_audio.NoteName.

Pitch module-attribute

Pitch = _AudioPitch

A pitch: a note name such as 'C#4' or a MIDI number from 0 to 127.

Maps to xnano_audio.Pitch.

TerminalAudioError module-attribute

TerminalAudioError = _AudioTerminalAudioError

Raised when a sound device or stream fails.

Maps to xnano_audio.TerminalAudioError.

TerminalAudioUnavailableError module-attribute

TerminalAudioUnavailableError = _AudioTerminalAudioUnavailableError

Raised when this computer has no sound device, or this build has no device support.

Maps to xnano_audio.TerminalAudioUnavailableError.

instrument_names module-attribute

instrument_names = _audio_instrument_names

The name of every built-in instrument, in catalog order.

Maps to xnano_audio.instrument_names.

Audio dataclass

Audio(terminal_sound: TerminalSound, /, *, symbol: str | None = None)

Audio to play: a recording loaded from a file, samples you made, or what a canvas played.

Load a WAV, MP3, FLAC, Ogg Vorbis or MP4/AAC file with load_audio, make audio from samples with from_samples, or take what a canvas from new() played with Speaker.render. Play it with Speaker.play or play, or give it a symbol and play it by name. Audio is mono, and all of it is kept in memory, so a long song takes memory in proportion to its length.

Attributes:

  • terminal_sound (TerminalSound) –

    The audio as an xnano-audio sound, for the functions of that package. Maps to xnano_audio.TerminalSound.

  • symbol (str | None) –

    The name the audio is registered under in symbols, or None. play('kick') plays the audio registered as 'kick'.

  • sample_rate (int) –

    How many samples it has per second.

  • duration_milliseconds (float) –

    How long it lasts, in milliseconds.

  • peak (float) –

    The largest absolute sample: 0.0 for silence, above 1.0 when it clips.

  • region (Region[float]) –

    The audio on the timeline as a piano roll: a Region that starts at beat 0, lasts as long as the audio at 120 beats per minute and covers the single row of middle C, because audio has no pitch of its own.

Examples:

import xnano

audio = xnano.Audio.from_samples([0.0, 0.5, -0.5, 0.0])
assert (audio.sample_rate, audio.peak) == (44100, 0.5)
assert (audio.region.y, audio.region.height) == (60, 1)

Make audio from a sound made with xnano-audio.

For a file use load_audio, and for samples from_samples.

Parameters:

  • terminal_sound (TerminalSound) –

    A TerminalSound, such as one that an xnano-audio function rendered.

  • symbol (str | None, default: None ) –

    A name to register the audio under in symbols, so play(name) plays it.

Raises:

  • ImportError –

    xnano-audio is not installed. Install it with pip install "xnano[audio]".

  • TypeError –

    terminal_sound is not a TerminalSound.

  • ValueError –

    symbol cannot be a symbol name, or another kind of value already has it.

Methods:

  • from_samples –

    Make audio from samples: numbers from -1.0 to 1.0, one per instant.

  • samples –

    A copy of the samples, in order.

Source code in xnano/audio/_audio.py
def __init__(
    self, terminal_sound: TerminalSound, /, *, symbol: str | None = None
) -> None:
    """
    Make audio from a sound made with ``xnano-audio``.

    For a file use [`load_audio`][xnano.load_audio], and for samples
    [`from_samples`][xnano.Audio.from_samples].

    Args:
        terminal_sound: A [`TerminalSound`][xnano_audio.TerminalSound], such as one
            that an ``xnano-audio`` function rendered.
        symbol: A name to register the audio under in [`symbols`][xnano.symbols], so
            ``play(name)`` plays it.

    Raises:
        ImportError: ``xnano-audio`` is not installed. Install it with
            ``pip install "xnano[audio]"``.
        TypeError: ``terminal_sound`` is not a ``TerminalSound``.
        ValueError: ``symbol`` cannot be a symbol name, or another kind of value
            already has it.
    """
    module = require('audio', needed_for='xnano.Audio')
    if not isinstance(terminal_sound, module.TerminalSound):
        raise TypeError(
            f'Audio wraps an xnano_audio.TerminalSound, but got '
            f'{type(terminal_sound).__name__}. Load a file with '
            f'xnano.load_audio("song.mp3"), or make audio from samples with '
            f'xnano.Audio.from_samples([0.0, 0.5, -0.5]).'
        )
    object.__setattr__(self, 'terminal_sound', terminal_sound)
    object.__setattr__(self, 'symbol', symbol)
    if symbol is not None:
        symbols.register(symbol, self)

terminal_sound instance-attribute

terminal_sound: TerminalSound

The audio as an xnano-audio sound. Maps to xnano_audio.TerminalSound.

symbol instance-attribute

symbol: str | None

The registered symbol name, or None.

sample_rate property

sample_rate: int

How many samples the audio has per second.

duration_milliseconds property

duration_milliseconds: float

How long the audio lasts, in milliseconds.

peak property

peak: float

The largest absolute sample: 0.0 for silence, above 1.0 when it clips.

region property

region: Region[float]

The audio on the timeline as a piano roll.

The region starts at beat 0 and lasts as long as the audio does at 120 beats per minute, the tempo of play when no canvas is running, so its milliseconds view is the duration of the audio. Audio has no pitch of its own, so the region covers the one row of middle C (60). context.region of a hook on a playable measures at the tempo of the canvas instead.

Examples:

import xnano

audio = xnano.Audio.from_samples([0.0] * 44100)
assert audio.region.milliseconds.width == 1000.0
assert (audio.region.y, audio.region.height) == (60, 1)

from_samples classmethod

from_samples(samples: Sequence[float], /, *, sample_rate: int = 44100, symbol: str | None = None) -> Audio

Make audio from samples: numbers from -1.0 to 1.0, one per instant.

Parameters:

  • samples (Sequence[float]) –

    The samples, in order.

  • sample_rate (int, default: 44100 ) –

    How many samples there are per second.

  • symbol (str | None, default: None ) –

    A name to register the audio under in symbols, so play(name) plays it.

Returns:

Raises:

  • ImportError –

    xnano-audio is not installed. Install it with pip install "xnano[audio]".

  • ValueError –

    samples is empty, or sample_rate is not above 0.

Examples:

import math

import xnano

tone = [math.sin(index / 10) for index in range(44100)]
audio = xnano.Audio.from_samples(tone, symbol='tone')
assert audio.duration_milliseconds == 1000.0
Source code in xnano/audio/_audio.py
@classmethod
def from_samples(
    cls,
    samples: Sequence[float],
    /,
    *,
    sample_rate: int = 44100,
    symbol: str | None = None,
) -> Audio:
    """
    Make audio from samples: numbers from ``-1.0`` to ``1.0``, one per instant.

    Args:
        samples: The samples, in order.
        sample_rate: How many samples there are per second.
        symbol: A name to register the audio under in [`symbols`][xnano.symbols], so
            ``play(name)`` plays it.

    Returns:
        The [`Audio`][xnano.Audio].

    Raises:
        ImportError: ``xnano-audio`` is not installed. Install it with
            ``pip install "xnano[audio]"``.
        ValueError: ``samples`` is empty, or ``sample_rate`` is not above 0.

    Examples:
        ```python
        import math

        import xnano

        tone = [math.sin(index / 10) for index in range(44100)]
        audio = xnano.Audio.from_samples(tone, symbol='tone')
        assert audio.duration_milliseconds == 1000.0
        ```
    """
    module = require('audio', needed_for='xnano.Audio.from_samples')
    values = samples if isinstance(samples, list) else list(samples)
    return cls(
        module.TerminalSound.from_samples(values, sample_rate=sample_rate),
        symbol=symbol,
    )

samples

samples() -> list[float]

A copy of the samples, in order.

Source code in xnano/audio/_audio.py
def samples(self) -> list[float]:
    """A copy of the samples, in order."""
    return self.terminal_sound.samples()

Note dataclass

Note(pitch: Pitch | tuple[Pitch, ...], *, beats: float = 1.0, instrument: InstrumentName = 'piano', velocity: float = 0.8, effects: tuple[PlayableEffectSpecification, ...] = (), symbol: str | None = None)

A note, or a chord, to play: a pitch, how long it lasts and how it sounds.

A note is a plain value. It needs no sound device, no canvas and not even the audio extra to be created, so a song can be defined at the top of a module and played later with play or Speaker.play. A sequence of notes plays one after another. symbol registers the note under a name, so play('kick') finds it.

Attributes:

  • pitch (Pitch | tuple[Pitch, ...]) –

    A note name such as 'C#4', a MIDI number from 0 to 127 (60 is middle C), or a tuple of them for a chord.

  • beats (float) –

    How long the note is held, in beats at the canvas's tempo. A beat is half a second at 120 beats per minute.

  • instrument (InstrumentName) –

    A built-in instrument, from instrument_names.

  • velocity (float) –

    How hard the note is played, from 0.0 to 1.0.

  • effects (tuple[PlayableEffectSpecification, ...]) –

    Sound effects as dictionaries with a kind key, such as {'kind': 'audio.reverb', 'mix': 0.4}.

  • symbol (str | None) –

    The name the note is registered under in symbols, or None.

  • region (Region[float]) –

    The note on the timeline as a piano roll: a Region that starts at beat 0, lasts beats and spans the semitones from the lowest to the highest pitch.

Raises:

  • TypeError –

    The pitch is not a note name or a number, or an effect is not a dictionary.

  • ValueError –

    The pitch is not valid, beats is not above 0, velocity is not from 0.0 to 1.0, or the instrument is unknown (checked when the audio extra is installed, and otherwise when the note is played).

Examples:

import xnano

chord = xnano.Note(('C4', 'E4', 'G4'), beats=2.0, instrument='bell')
assert chord.beats == 2.0
assert chord.region.y == 60
assert chord.region.height == 8
assert chord.region.width == 2.0
assert chord.region.sixteenths.width == 8.0
assert chord.region.milliseconds.width == 1000.0
with xnano.new(width=8, height=1) as canvas:
    canvas.speaker.play([chord, xnano.Note('C5')])
    canvas.clock.step(delta_seconds=1.0)
    assert canvas.speaker.render().duration_milliseconds == 1000.0

Methods:

  • __post_init__ –

    Check the values and register the symbol.

  • __hash__ –

    Hash the note by its values, so notes that are equal hash equal.

  • __xnano_play__ –

    Return this note, so a note is playable like any other component.

pitch instance-attribute

pitch: Pitch | tuple[Pitch, ...]

A note name, a MIDI number, or a tuple of them for a chord.

beats class-attribute instance-attribute

beats: float = 1.0

How long the note is held, in beats.

instrument class-attribute instance-attribute

instrument: InstrumentName = 'piano'

The built-in instrument.

velocity class-attribute instance-attribute

velocity: float = 0.8

How hard the note is played, from 0.0 to 1.0.

effects class-attribute instance-attribute

effects: tuple[PlayableEffectSpecification, ...] = ()

The sound effects, as dictionaries with a kind key.

symbol class-attribute instance-attribute

symbol: str | None = None

The registered symbol name, or None.

region property

region: Region[float]

The note on the timeline as a piano roll, on its own.

The region starts at beat 0 and lasts beats. Its y is the lowest pitch as a MIDI number and its height the semitones from the lowest to the highest pitch, so a chord spans several rows and a single note one. Its milliseconds view assumes 120 beats per minute, the tempo of play when no canvas is running; context.region of a hook on a playable measures at the tempo of the canvas instead.

Examples:

import xnano

region = xnano.Note('A4', beats=0.5).region
assert (region.x, region.width) == (0.0, 0.5)
assert (region.y, region.height) == (69, 1)

__post_init__

__post_init__() -> None

Check the values and register the symbol.

Source code in xnano/audio/_notes.py
def __post_init__(self) -> None:
    """Check the values and register the symbol."""
    pitch = self.pitch
    if isinstance(pitch, (list, tuple)):
        if not pitch:
            raise ValueError(
                'A chord needs at least one pitch, but got an empty one. Pass '
                'Note(("C4", "E4", "G4")) for a chord or Note("C4") for one note.'
            )
        pitch = tuple(pitch)
        for each in pitch:
            _check_pitch(each)
        object.__setattr__(self, 'pitch', pitch)
    else:
        _check_pitch(pitch)
    if (
        isinstance(self.beats, bool)
        or not isinstance(self.beats, (int, float))
        or not math.isfinite(self.beats)
        or self.beats <= 0
    ):
        raise ValueError(
            f'beats must be a number above 0, but was {self.beats!r}. Use 1.0 for one '
            f'beat or 0.5 for half a beat.'
        )
    if isinstance(self.velocity, bool) or not isinstance(self.velocity, (int, float)):
        raise ValueError(
            f'velocity must be a number from 0.0 to 1.0, but was {self.velocity!r}. Use '
            f'0.8 for an ordinary note.'
        )
    if not isinstance(self.instrument, str):
        raise ValueError(
            f'instrument must be the name of a built-in instrument, such as "piano", '
            f'but was {self.instrument!r}.'
        )
    if not 0.0 <= self.velocity <= 1.0:
        raise ValueError(
            f'velocity must be from 0.0 to 1.0, but was {self.velocity!r}. Use 0.8 for '
            f'an ordinary note.'
        )
    audio = _installed_audio()
    if audio is not None:
        names = audio.instrument_names()
        if self.instrument not in names:
            raise ValueError(
                f'{self.instrument!r} is not an instrument. Use one of: '
                f'{", ".join(names)}.'
            )
    effects = effect_sequence(self.effects, 'playable')
    for effect in effects:
        normalize_effect(effect, 'playable')
    object.__setattr__(self, 'effects', effects)
    if self.symbol is not None:
        symbols.register(self.symbol, self)

__hash__

__hash__() -> int

Hash the note by its values, so notes that are equal hash equal.

Source code in xnano/audio/_notes.py
def __hash__(self) -> int:
    """Hash the note by its values, so notes that are equal hash equal."""
    return hash(
        (
            self.pitch,
            self.beats,
            self.instrument,
            self.velocity,
            _hashable(self.effects),
            self.symbol,
        )
    )

__xnano_play__

__xnano_play__(context: Context) -> Note

Return this note, so a note is playable like any other component.

Source code in xnano/audio/_notes.py
def __xnano_play__(self, context: Context) -> Note:
    """Return this note, so a note is playable like any other component."""
    return self

PlayHandle

PlayHandle(*, clock: Callable[[], float], end_seconds: float, cancel: Callable[[], None] | None = None, build_region: Callable[..., Region[float]] | None = None, region_arguments: tuple[object, ...] = ())

What play returns: tells whether the sound is over and can cut it short.

Attributes:

  • is_finished (bool) –

    Whether the sound has ended or the handle was removed. On a canvas from new this follows the canvas's clock; on a device it follows the real time since the sound was handed over.

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    handle = canvas.speaker.play(xnano.Note('C4', beats=1.0))
    assert not handle.is_finished
    handle.remove()
    assert handle.is_finished

Make a handle. Use the handle that play returns instead of calling this.

Parameters:

  • clock (Callable[[], float]) –

    Returns the current time in seconds.

  • end_seconds (float) –

    The time on that clock at which the sound is over.

  • cancel (Callable[[], None] | None, default: None ) –

    Called once by remove().

  • build_region (Callable[..., Region[float]] | None, default: None ) –

    Returns where the sound is on the timeline of the canvas it plays on, which is what context.region of a playable reports; None when that is not known. It is called with region_arguments at most once, when the region is first read.

  • region_arguments (tuple[object, ...], default: () ) –

    What build_region is called with, captured when the sound is played.

Methods:

  • remove –

    Stop the sound from playing any further, as far as it has not been heard yet.

Source code in xnano/audio/_notes.py
def __init__(
    self,
    *,
    clock: Callable[[], float],
    end_seconds: float,
    cancel: Callable[[], None] | None = None,
    build_region: Callable[..., Region[float]] | None = None,
    region_arguments: tuple[object, ...] = (),
) -> None:
    """
    Make a handle. Use the handle that ``play`` returns instead of calling this.

    Args:
        clock: Returns the current time in seconds.
        end_seconds: The time on that clock at which the sound is over.
        cancel: Called once by ``remove()``.
        build_region: Returns where the sound is on the timeline of the canvas it plays
            on, which is what ``context.region`` of a playable reports; ``None`` when
            that is not known. It is called with ``region_arguments`` at most once, when
            the region is first read.
        region_arguments: What ``build_region`` is called with, captured when the sound
            is played.
    """
    self._clock = clock
    self._end_seconds = end_seconds
    self._cancel = cancel
    self._is_removed = False
    self._build_region = build_region
    self._region_arguments = region_arguments
    self._region_value: Region[float] | None = None

is_finished property

is_finished: bool

Whether the sound ended or the handle was removed.

remove

remove() -> None

Stop the sound from playing any further, as far as it has not been heard yet.

On a canvas from new the part that has not been rendered by render_sound is dropped. On a device a sound that was already handed to the output plays to its end, and one still waiting for its beat never starts. Removing twice does nothing.

Source code in xnano/audio/_notes.py
def remove(self) -> None:
    """
    Stop the sound from playing any further, as far as it has not been heard yet.

    On a canvas from [`new`][xnano.new] the part that has not been rendered by
    [`render_sound`][xnano.devices.Speaker.render] is dropped. On a device a sound
    that was already handed to the output plays to its end, and one still waiting for its
    beat never starts. Removing twice does nothing.
    """
    if self._is_removed:
        return
    self._is_removed = True
    if self._cancel is not None:
        self._cancel()

Melody dataclass

Melody(text: str, *, bpm: float = 120.0, beats: float = 1.0, symbol: str | None = None)

Notes in order, written as text and parsed: 'C4 E4 G4:2 rest C5+E5+G5'.

A melody is the parsed form of the melody text that play also accepts. Make one when you want to look at the notes, reuse the same melody many times, or give it a symbol so play('theme') plays it. A melody plays at its own bpm, whatever the tempo of the canvas it is played on.

In the text, C4 is a note, C4:0.5 holds it for half a beat, C4+E4+G4 is a chord, rest (or -) is a silence that takes :beats the same way, and | is a bar line that only makes the text easier to read.

Maps to xnano_audio.TerminalMelody.

Attributes:

  • text (str) –

    The melody text it was made from.

  • bpm (float) –

    The tempo it plays at, in beats per minute.

  • beats (float) –

    The length in beats of a note that gives none.

  • score (TerminalMelody) –

    The parsed melody: its notes, tempo map and time signature.

  • symbol (str | None) –

    The name the melody is registered under in symbols, or None.

  • length_beats (float) –

    The length of the melody in beats.

  • duration_seconds (float) –

    The length of the melody in seconds, at its tempo.

  • region (Region[float]) –

    The melody on the timeline as a piano roll: a Region that starts at beat 0, lasts length_beats and spans the semitones from its lowest to its highest pitch. Its milliseconds view follows the tempo of the melody.

Examples:

import xnano

melody = xnano.audio.Melody('C4 E4 G4:2', bpm=120)
assert melody.length_beats == 4.0
assert melody.region.width == 4.0
assert melody.region.height == 8
with xnano.new(width=8, height=1) as canvas:
    canvas.speaker.play(melody)
    canvas.clock.step(delta_seconds=1.0)
    assert canvas.speaker.render().peak > 0.0

Parse melody text.

Parameters:

  • text (str) –

    Notes separated by spaces, such as 'C4 E4 G4:2 rest C5+E5+G5'.

  • bpm (float, default: 120.0 ) –

    The tempo the melody plays at, in beats per minute.

  • beats (float, default: 1.0 ) –

    The length in beats of a note that gives none of its own.

  • symbol (str | None, default: None ) –

    A name to register the melody under in symbols, so play(name) plays it.

Raises:

  • ImportError –

    xnano-audio is not installed. Install it with pip install "xnano[audio]".

  • TypeError –

    text is not a str.

  • ValueError –

    bpm or beats is not a finite number above 0, an entry of the text is not a note, a length, a chord or a rest, or symbol cannot be a symbol name, or another kind of value already has it.

Source code in xnano/audio/_melodies.py
def __init__(
    self,
    text: str,
    *,
    bpm: float = 120.0,
    beats: float = 1.0,
    symbol: str | None = None,
) -> None:
    """
    Parse melody text.

    Args:
        text: Notes separated by spaces, such as ``'C4 E4 G4:2 rest C5+E5+G5'``.
        bpm: The tempo the melody plays at, in beats per minute.
        beats: The length in beats of a note that gives none of its own.
        symbol: A name to register the melody under in [`symbols`][xnano.symbols], so
            ``play(name)`` plays it.

    Raises:
        ImportError: ``xnano-audio`` is not installed. Install it with
            ``pip install "xnano[audio]"``.
        TypeError: ``text`` is not a ``str``.
        ValueError: ``bpm`` or ``beats`` is not a finite number above 0, an entry of the
            text is not a note, a length, a chord or a rest, or ``symbol`` cannot be a
            symbol name, or another kind of value already has it.
    """
    if not isinstance(text, str):
        raise TypeError(
            f'Melody needs melody text such as "C4 E4 G4:2", but got {text!r}. Pass notes '
            f'separated by spaces.'
        )
    tempo = _check_positive_number(
        'bpm', bpm, example='Use 120.0 for an ordinary tempo.'
    )
    length = _check_positive_number(
        'beats', beats, example='Use 1.0 for a note that lasts one beat.'
    )
    score = parse_melody_text(text, tempo, length)
    object.__setattr__(self, 'text', text)
    object.__setattr__(self, 'bpm', tempo)
    object.__setattr__(self, 'beats', length)
    object.__setattr__(self, 'score', score)
    object.__setattr__(self, 'symbol', symbol)
    if symbol is not None:
        symbols.register(symbol, self)

text instance-attribute

text: str

The melody text it was made from.

bpm instance-attribute

bpm: float

The tempo it plays at, in beats per minute.

beats instance-attribute

beats: float

The length in beats of a note that gives none.

score class-attribute instance-attribute

score: TerminalMelody = dataclasses.field(compare=False, hash=False)

The parsed melody: its notes, tempo map and time signature.

Maps to xnano_audio.TerminalMelody.

symbol instance-attribute

symbol: str | None

The registered symbol name, or None.

length_beats property

length_beats: float

The length of the melody in beats, from the start of the first note to the end of the last.

duration_seconds property

duration_seconds: float

The length of the melody in seconds at its bpm.

region property

region: Region[float]

The melody on the timeline as a piano roll.

The region starts at beat 0 and lasts length_beats. Its y is the lowest pitch as a MIDI number and its height the semitones from the lowest to the highest pitch; a melody of only rests spans none. Its milliseconds view follows the tempo of the melody, including any change of tempo in it.

Examples:

import xnano

region = xnano.audio.Melody('C4 rest E4:2', bpm=60).region
assert (region.width, region.y, region.height) == (4.0, 60, 5)
assert region.milliseconds.width == 4000.0

Microphone

Microphone(canvas: Canvas[object, object])

The canvas's microphone: how loud the sound at the default input device is.

Get it from AudioDevice.microphone, which is canvas.microphone. The input device is opened the first time something reads the level, the level history, the sample rate or the channel count. On a computer without an input device, without permission to record, or on a canvas from new(), which has no device, the level is 0 and the history is empty.

The level is an expression, so it drives anything an expression can: a position, a size, a color, an effect.

Maps to xnano_audio.TerminalMicrophone.

Attributes:

  • level (NumericExpression) –

    The current level from 0.0 to 1.0, as an expression.

  • is_open (bool) –

    Whether the input device is open. Reading it never opens the device.

  • sample_rate (int | None) –

    The input device's sample rate in hertz, or None when there is no input device.

  • channels (int | None) –

    The input device's channel count, or None when there is no input device.

Examples:

import xnano

with xnano.new(width=20, height=1) as canvas:
    microphone = canvas.microphone
    assert canvas.evaluate(microphone.level) == 0.0
    assert not microphone.is_open
    assert microphone.sample_rate is None

Create the microphone of a canvas. Use canvas.microphone instead of calling this.

Parameters:

Methods:

  • level_history –

    Return the last count microphone levels, oldest first.

Source code in xnano/audio/_microphone.py
def __init__(self, canvas: Canvas[object, object]) -> None:
    """
    Create the microphone of a canvas. Use ``canvas.microphone`` instead of calling this.

    Args:
        canvas: The canvas the microphone belongs to.
    """
    self._canvas = canvas
    self._device: TerminalMicrophone | None = None
    self._is_unavailable = False
    self._level = _external(_LEVEL_NAME, True)

level property

level: NumericExpression

The microphone's current level from 0.0 to 1.0, as an expression.

Reading it opens the default input device the first time a frame evaluates it. Without an input device, without permission, or on a canvas without a device, the level is 0.

Examples:

import xnano

with xnano.new(width=20, height=2) as canvas:
    meter = canvas.screen.write('#')
    meter.x = canvas.microphone.level * 19
    assert canvas.evaluate(canvas.microphone.level) == 0.0

is_open property

is_open: bool

Whether the input device is open and listening.

This only reports; it never opens the device, so it is False until the level, the level history, the sample rate or the channel count has been read.

sample_rate property

sample_rate: int | None

The input device's sample rate in hertz.

Opens the default input device if it is not open yet. It is None without an input device, without permission, or on a canvas without a device.

channels property

channels: int | None

The input device's channel count.

Opens the default input device if it is not open yet. It is None without an input device, without permission, or on a canvas without a device.

level_history

level_history(count: int) -> list[float]

Return the last count microphone levels, oldest first.

Opens the default input device if it is not open yet. The list is empty without an input device, without permission, or on a canvas without a device.

Parameters:

  • count (int) –

    How many levels to return.

Returns:

  • list[float] –

    The levels, each from 0.0 to 1.0, one for each buffer of sound the device has

  • list[float] –

    delivered.

Source code in xnano/audio/_microphone.py
def level_history(self, count: int) -> list[float]:
    """
    Return the last ``count`` microphone levels, oldest first.

    Opens the default input device if it is not open yet. The list is empty without an
    input device, without permission, or on a canvas without a device.

    Args:
        count: How many levels to return.

    Returns:
        The levels, each from 0.0 to 1.0, one for each buffer of sound the device has
        delivered.
    """
    canvas = self._canvas
    canvas._require_open()

    def read() -> list[float]:
        device = self._open()
        return [] if device is None else device.level_history(count)

    return canvas._host.call(read)

load_audio

load_audio(file: PathLike[str] | str | bytes, /, *, symbol: str | None = None) -> Audio

Load audio from an audio file: its path, or its bytes.

WAV, MP3, FLAC, Ogg Vorbis and MP4/AAC files are read, and the format is recognised from the content of the file, whatever its name. The whole file is decoded into mono audio. Play the result with canvas.speaker.play(audio), or give it a symbol and play it by name.

Parameters:

  • file (PathLike[str] | str | bytes) –

    The path of an audio file, or the bytes of one.

  • symbol (str | None, default: None ) –

    A name to register the audio under in symbols, so play(name) plays it.

Returns:

Raises:

  • ImportError –

    xnano-audio is not installed. Install it with pip install "xnano[audio]".

  • TypeError –

    file is neither a path nor bytes.

  • FileNotFoundError –

    No file exists at the path.

  • ValueError –

    The file is not a WAV, MP3, FLAC, Ogg Vorbis or MP4/AAC file that xnano can read, or symbol cannot be a symbol name, or another kind of value already has it.

Examples:

import io
import wave

import xnano

data = io.BytesIO()
with wave.open(data, 'wb') as writer:
    writer.setnchannels(1)
    writer.setsampwidth(2)
    writer.setframerate(8000)
    writer.writeframes(bytes([0, 64]) * 800)
beep = xnano.load_audio(data.getvalue(), symbol='beep')
assert beep.duration_milliseconds == 100.0
with xnano.new(width=8, height=1) as canvas:
    canvas.speaker.play('beep')
    canvas.clock.step(delta_seconds=0.1)
    assert canvas.speaker.render().peak > 0.0
Source code in xnano/audio/_audio.py
def load_audio(
    file: os.PathLike[str] | str | bytes,
    /,
    *,
    symbol: str | None = None,
) -> Audio:
    """
    Load audio from an audio file: its path, or its bytes.

    WAV, MP3, FLAC, Ogg Vorbis and MP4/AAC files are read, and the format is recognised from
    the content of the file, whatever its name. The whole file is decoded into mono audio.
    Play the result with ``canvas.speaker.play(audio)``, or give it a ``symbol`` and play it
    by name.

    Args:
        file: The path of an audio file, or the bytes of one.
        symbol: A name to register the audio under in [`symbols`][xnano.symbols], so
            ``play(name)`` plays it.

    Returns:
        The [`Audio`][xnano.Audio].

    Raises:
        ImportError: ``xnano-audio`` is not installed. Install it with
            ``pip install "xnano[audio]"``.
        TypeError: ``file`` is neither a path nor bytes.
        FileNotFoundError: No file exists at the path.
        ValueError: The file is not a WAV, MP3, FLAC, Ogg Vorbis or MP4/AAC file that xnano
            can read, or ``symbol`` cannot be a symbol name, or another kind of value
            already has it.

    Examples:
        ```python
        import io
        import wave

        import xnano

        data = io.BytesIO()
        with wave.open(data, 'wb') as writer:
            writer.setnchannels(1)
            writer.setsampwidth(2)
            writer.setframerate(8000)
            writer.writeframes(bytes([0, 64]) * 800)
        beep = xnano.load_audio(data.getvalue(), symbol='beep')
        assert beep.duration_milliseconds == 100.0
        with xnano.new(width=8, height=1) as canvas:
            canvas.speaker.play('beep')
            canvas.clock.step(delta_seconds=0.1)
            assert canvas.speaker.render().peak > 0.0
        ```
    """
    module = require('audio', needed_for='xnano.load_audio')
    if isinstance(file, bytes):
        terminal_sound = _decode_audio_bytes(module, file)
    elif isinstance(file, (str, os.PathLike)):
        path = pathlib.Path(file)
        if not path.is_file():
            raise FileNotFoundError(
                f'load_audio could not load {str(path)!r}, because no audio file exists '
                f'there. Check the path, or pass the bytes of the file.'
            )
        terminal_sound = _decode_audio_path(module, path)
    else:
        raise TypeError(
            f'load_audio needs the path of an audio file or the bytes of one, but got '
            f'{type(file).__name__}. Pass xnano.load_audio("song.mp3"); for samples use '
            f'xnano.Audio.from_samples(), and for an xnano_audio.TerminalSound use '
            f'xnano.Audio(terminal_sound).'
        )
    return Audio(terminal_sound, symbol=symbol)

play

play(playable: PlaySource, /, **options: Unpack[PlayOptions]) -> PlayHandle

Play a note, a sound, a symbol name, a melody or a sequence of those.

The sound goes to the running canvas (see active); with no canvas running it goes to this computer's sound output. On a canvas from new, which has a clock you move, the sound is recorded and makes no noise: read it with canvas.speaker.render().

A str is a symbol name first, so play('kick') plays the note or sound registered with symbol='kick'. Any other str is a note name such as 'C#4', a frequency such as '440hz' or melody text: notes separated by spaces, :2 holds a note for two beats, rest is a silence, + joins a chord and | marks a bar, as in 'C4 E4 G4:2 rest C5+E5+G5'. A sequence plays one after another. An option replaces the same value on a Note, so play(Note('C4'), instrument='violin') plays the violin.

Parameters:

  • playable (PlaySource) –

    What to play.

  • **options (Unpack[PlayOptions], default: {} ) –

    See PlayOptions: instrument, velocity, effects, volume, pan, at_beat and beats, the length in beats of a note name, a number or a Note.

Returns:

Raises:

  • ImportError –

    xnano-audio is not installed. Install it with pip install "xnano[audio]".

  • TerminalAudioUnavailableError –

    No canvas is running and this computer has no sound output device.

  • ValueError –

    An option is out of range, or a str is neither a symbol, a note name nor melody text. The message lists the known sound symbols.

Examples:

import xnano

with xnano.new(width=8, height=1) as canvas:
    xnano.play([xnano.Note('C4'), xnano.Note('E4'), xnano.Note('G4')])
    canvas.clock.step(delta_seconds=1.5)
    assert canvas.speaker.render().peak > 0.0
Source code in xnano/audio/_notes.py
def play(playable: PlaySource, /, **options: Unpack[PlayOptions]) -> PlayHandle:
    """
    Play a note, a sound, a symbol name, a melody or a sequence of those.

    The sound goes to the running canvas (see [`active`][xnano.active]); with no canvas
    running it goes to this computer's sound output. On a canvas from [`new`][xnano.new],
    which has a clock you move, the sound is recorded and makes no noise: read it with
    ``canvas.speaker.render()``.

    A ``str`` is a symbol name first, so ``play('kick')`` plays the note or sound registered
    with ``symbol='kick'``. Any other ``str`` is a note name such as ``'C#4'``, a frequency such
    as ``'440hz'`` or melody text: notes separated by spaces, ``:2`` holds a note for two
    beats, ``rest`` is a silence, ``+`` joins a chord and ``|`` marks a bar, as in
    ``'C4 E4 G4:2 rest C5+E5+G5'``. A sequence plays one after another. An option replaces
    the same value on a [`Note`][xnano.Note], so ``play(Note('C4'), instrument='violin')``
    plays the violin.

    Args:
        playable: What to play.
        **options: See [`PlayOptions`][xnano.devices.PlayOptions]: ``instrument``, ``velocity``,
            ``effects``, ``volume``, ``pan``, ``at_beat`` and ``beats``, the length in beats
            of a note name, a number or a ``Note``.

    Returns:
        A [`PlayHandle`][xnano.audio.PlayHandle].

    Raises:
        ImportError: ``xnano-audio`` is not installed. Install it with
            ``pip install "xnano[audio]"``.
        TerminalAudioUnavailableError: No canvas is running and this computer has no sound
            output device.
        ValueError: An option is out of range, or a ``str`` is neither a symbol, a note name
            nor melody text. The message lists the known sound symbols.

    Examples:
        ```python
        import xnano

        with xnano.new(width=8, height=1) as canvas:
            xnano.play([xnano.Note('C4'), xnano.Note('E4'), xnano.Note('G4')])
            canvas.clock.step(delta_seconds=1.5)
            assert canvas.speaker.render().peak > 0.0
        ```
    """
    from xnano.canvas import active

    canvas = active(is_required=False)
    if canvas is not None:
        return canvas.speaker.play(playable, **options)
    return _default_player().play(playable, **options)

__getattr__

__getattr__(name: str) -> object

Import a name that needs the audio extra the first time it is read, then keep it.

Source code in xnano/audio/__init__.py
def __getattr__(name: str) -> object:
    """Import a name that needs the ``audio`` extra the first time it is read, then keep it."""
    module_name = _LAZY_NAMES.get(name)
    if module_name is None:
        raise AttributeError(
            f'xnano.audio has no name {name!r}. Its names are {", ".join(__all__)}.'
        )
    _optional.require('audio', needed_for=f'xnano.audio.{name}')
    value = getattr(importlib.import_module(module_name), name)
    globals()[name] = value
    return value

__dir__

__dir__() -> list[str]

The public names of the module, including the ones that are imported when first read.

Source code in xnano/audio/__init__.py
def __dir__() -> list[str]:
    """The public names of the module, including the ones that are imported when first read."""
    return sorted(__all__)