PHONOTENSOR / v0.2.2

API reference

Find the function you need. Signatures, defaults, and return types extracted from the published Python package.

Import core classes from phonotensor, operations from phonotensor.ops, and formatting helpers from phonotensor.fmt. Source links point to the matching GitHub commit. Internal backend classes and Python special methods are excluded.

186 of 186 entries

phonotensor.collector

Deprecated compatibility API. Prefer MicrophoneSource and AudioPlayer in new code. read() and collect() require an active open() context.

phonotensor.core.config

Frozen configuration dataclasses and stream enums. A block_size of 0 lets the backend choose its buffer size.

StreamConfig

class
StreamConfig
sample_rate: int = 44100
channels: int = 1
sample_format: SampleFormat = SampleFormat.FLOAT32
block_size: int = 0
latency: float | None = None
View implementation

DeviceConfig

class
DeviceConfig
stream_config: StreamConfig = field(default_factory=StreamConfig)
mode: StreamMode = StreamMode.INPUT
device_name: str | None = None
device_index: int | None = None
View implementation

phonotensor.core.feature_tensor

Feature data is shaped (frames, features) and can be complex. Frame timing is available when hop_length is set. to_dict() exports metadata, not data.

FeatureTensor

method
FeatureTensor(data: Any, sample_rate: int, feature_type: str='custom', n_fft: int | None=None, hop_length: int | None=None) → None
View implementation

phonotensor.core.tensor

Audio samples are float32 arrays shaped (samples, channels). Time values are seconds; sample rates are Hz. Use to_numpy() for a writable copy.

phonotensor.device.device

Audio device information returned by backend device enumeration. Check input and output channel capabilities before opening a stream.

AudioDevice

class
AudioDevice
index: int
name: str
max_input_channels: int
max_output_channels: int
default_sample_rate: float
is_default_input: bool
is_default_output: bool
host_api_name: str
View implementation

phonotensor.exceptions

Library error hierarchy. External codec, NumPy, and OS exceptions are not always wrapped in PhonotensorError.

phonotensor.fmt.convert

Convert AudioTensor data to Python or serialized representations. Use matching from_dict/from_json helpers to restore audio with sample-rate metadata.

from_function

function
from_function(fn: Callable[[np.ndarray], np.ndarray], duration: float, sample_rate: int=44100, channels: int=1) → AudioTensor
View implementation

phonotensor.fmt.display

Text summaries and terminal-friendly sample or waveform displays. These helpers do not create graphical plots or play audio.

phonotensor.io.file

File paths may be strings or pathlib.Path values. WAV, FLAC, and OGG use soundfile; MP3 needs pydub and a separate FFmpeg installation.

phonotensor.io.mic

Local microphone capture through PortAudio. Construction checks permissions by default. Recording is synchronous; durations are seconds and silence threshold is linear RMS amplitude.

MicrophoneSource

method
MicrophoneSource(sample_rate: int=44100, channels: int=1, device: str | int | None=None, backend_type: AudioBackendType | None=None, skip_permission_check: bool=False) → None
View implementation

phonotensor.io.player

Local output through PortAudio. In 0.2.2, playback is synchronous even with blocking=False. play_numpy() infers channels from the data and ignores its channels argument.

AudioPlayer

method
AudioPlayer(device: str | int | None=None, backend_type: AudioBackendType | None=None, skip_permission_check: bool=False) → None
View implementation

phonotensor.io.text

JSON carries sample-rate metadata. CSV and text arrays need a sample rate on import. Rows represent samples, columns represent channels.

phonotensor.ops.analysis

Scalar analysis over audio samples. dB measurements use a full-scale reference of 1. Avoid empty input for reductions such as peak, min, and max.

phonotensor.ops.arithmetic

Unlike tensor operators, ops.add/subtract/multiply check sample rates and channels, then zero-pad the shorter input. mix() also pads lengths and defaults to equal averaging weights.

scale

function
scale(tensor: AudioTensor, factor: float) → AudioTensor

Multiply samples by a scalar factor.

View implementation

mix

function
mix(tensors: list[AudioTensor], weights: list[float] | None=None) → AudioTensor

Combine tensors using optional weights.

View implementation

phonotensor.ops.convolution

Convolution and correlation of audio signals. Paired inputs must have matching sample rates. Convolution reuses a mono kernel across channels; correlation downmixes input to mono. Convolution mode controls the output length.

convolve

function
convolve(tensor: AudioTensor, kernel: AudioTensor, mode: Any='full') → AudioTensor

Convolve signals per channel.

View implementation

auto_correlate

function
auto_correlate(tensor: AudioTensor) → AudioTensor

Downmix to mono, autocorrelate, normalize by maximum absolute correlation, and retain nonnegative lags.

View implementation

phonotensor.ops.edit

Time positions and durations are seconds. Concatenation and overlays require matching sample rates and channels. Use nonnegative offsets for overlays.

trim

function
trim(tensor: AudioTensor, start: float=0.0, end: float | None=None) → AudioTensor

Extract a time interval; bounds are clamped to the audio.

View implementation

pad

function
pad(tensor: AudioTensor, before: float=0.0, after: float=0.0) → AudioTensor

Add zero-valued samples before or after audio.

View implementation

split

function
split(tensor: AudioTensor, at: float) → tuple[AudioTensor, AudioTensor]

Split into two tensors at a time in seconds.

View implementation

repeat

function
repeat(tensor: AudioTensor, times: int) → AudioTensor

Repeat the signal a positive integer number of times.

View implementation

overlay

function
overlay(base: AudioTensor, layer: AudioTensor, offset: float=0.0) → AudioTensor

Add a layer at an offset, extending the output when necessary.

View implementation

silence

function
silence(duration: float, sample_rate: int=44100, channels: int=1) → AudioTensor

Create zero-valued audio.

View implementation

trim_silence

function
trim_silence(tensor: AudioTensor, threshold: float=0.01, pad_seconds: float=0.05) → AudioTensor

Remove quiet ends using a linear amplitude threshold, retaining optional padding.

View implementation

phonotensor.ops.envelope

Envelope and dynamics operations return AudioTensors. Inspect individual parameter names for time and level units; use positive attack and release values.

adsr

function
adsr(attack: float, decay: float, sustain_level: float, release: float, duration: float, sample_rate: int=44100) → AudioTensor

Create a mono attack-decay-sustain-release envelope. Times are seconds; keep stage durations within the total duration.

View implementation

compress

function
compress(tensor: AudioTensor, threshold: float=0.5, ratio: float=4.0) → AudioTensor

Reduce amplitudes above a linear threshold by ratio; this is samplewise processing without attack/release smoothing.

View implementation

expand

function
expand(tensor: AudioTensor, threshold: float=0.1, ratio: float=2.0) → AudioTensor

Divide samples below a linear amplitude threshold by ratio.

View implementation

gate

function
gate(tensor: AudioTensor, threshold: float=0.01) → AudioTensor

Set samples below the absolute amplitude threshold to zero.

View implementation

follow_envelope

function
follow_envelope(tensor: AudioTensor, attack: float=0.01, release: float=0.1) → AudioTensor

Track amplitude with attack and release times in seconds; returns a mono envelope.

View implementation

apply_envelope

function
apply_envelope(tensor: AudioTensor, envelope: AudioTensor) → AudioTensor

Multiply audio by a mono or channel-matched envelope. Uncovered trailing samples become zero. Sample rates are not checked; align them first.

View implementation

phonotensor.ops.features

Features use mono-downmixed STFT frames. Mel values are power; MFCC uses natural-log mel values and a custom cosine transform starting at coefficient 1.

mel_spectrogram

function
mel_spectrogram(tensor: AudioTensor, n_fft: int=2048, hop_length: int | None=None, n_mels: int=128, fmin: float=0.0, fmax: float | None=None) → FeatureTensor

Project STFT power onto triangular mel bands.

View implementation

mfcc

function
mfcc(tensor: AudioTensor, n_mfcc: int=13, n_mels: int=128, n_fft: int=2048, hop_length: int | None=None, fmin: float=0.0, fmax: float | None=None) → FeatureTensor

Compute coefficients from natural-log mel power using the package’s custom cosine transform.

View implementation

spectral_centroid

function
spectral_centroid(tensor: AudioTensor, n_fft: int=2048, hop_length: int | None=None) → FeatureTensor

Magnitude-weighted frequency center in Hz per frame.

View implementation

spectral_rolloff

function
spectral_rolloff(tensor: AudioTensor, threshold: float=0.85, n_fft: int=2048, hop_length: int | None=None) → FeatureTensor

Frequency below which the threshold fraction of frame power lies.

View implementation

spectral_flatness

function
spectral_flatness(tensor: AudioTensor, n_fft: int=2048, hop_length: int | None=None) → FeatureTensor

Ratio of geometric to arithmetic mean magnitude per frame.

View implementation

spectral_bandwidth

function
spectral_bandwidth(tensor: AudioTensor, n_fft: int=2048, hop_length: int | None=None, order: int=2) → FeatureTensor

Magnitude-weighted spread about the centroid in Hz.

View implementation

phonotensor.ops.filter

Causal filters operate per channel. Frequencies are Hz, strictly between zero and Nyquist. Butterworth filters use second-order sections; notch uses an IIR notch filter.

lowpass

function
lowpass(tensor: AudioTensor, cutoff: float, order: int=5) → AudioTensor

Butterworth low-pass filter.

View implementation

bandpass

function
bandpass(tensor: AudioTensor, low_cutoff: float, high_cutoff: float, order: int=5) → AudioTensor

Butterworth band-pass filter; low_cutoff must be below high_cutoff.

View implementation

bandstop

function
bandstop(tensor: AudioTensor, low_cutoff: float, high_cutoff: float, order: int=5) → AudioTensor

Butterworth band-stop filter.

View implementation

notch

function
notch(tensor: AudioTensor, freq: float, q: float=30.0) → AudioTensor

Reject a frequency with quality factor q.

View implementation

phonotensor.ops.generate

Generators return mono AudioTensors. Use positive durations, sample rates, and frequencies below Nyquist for meaningful sampled signals. The current pink_noise implementation does not establish a 1/f spectrum.

sine

function
sine(freq: float, duration: float, sample_rate: int=44100, amplitude: float=1.0) → AudioTensor

Generate a sine tone; frequency is in Hz.

View implementation

square

function
square(freq: float, duration: float, sample_rate: int=44100, amplitude: float=1.0) → AudioTensor

Generate a square wave from the sign of a sine wave.

View implementation

sawtooth

function
sawtooth(freq: float, duration: float, sample_rate: int=44100, amplitude: float=1.0) → AudioTensor

Generate a sawtooth wave.

View implementation

triangle

function
triangle(freq: float, duration: float, sample_rate: int=44100, amplitude: float=1.0) → AudioTensor

Generate a triangle wave.

View implementation

impulse

function
impulse(duration: float, sample_rate: int=44100, amplitude: float=1.0) → AudioTensor

Create zeros with an impulse at the first sample.

View implementation

white_noise

function
white_noise(duration: float, sample_rate: int=44100, amplitude: float=1.0, seed: int | None=None) → AudioTensor

Generate uniform random noise with an optional reproducible seed.

View implementation

pink_noise

function
pink_noise(duration: float, sample_rate: int=44100, amplitude: float=1.0, seed: int | None=None) → AudioTensor

Generate normalized summed Gaussian noise. The current implementation is not verified pink noise.

View implementation

sweep

function
sweep(start_freq: float, end_freq: float, duration: float, sample_rate: int=44100, amplitude: float=1.0) → AudioTensor

Generate a sine sweep with linearly changing frequency.

View implementation

phonotensor.ops.pitch

Pitch and time operations downmix to mono and duplicate output channels. Stereo separation is not preserved. rate must be positive; use signals long enough for the 2048-sample analysis window.

pitch_shift

function
pitch_shift(tensor: AudioTensor, semitones: float) → AudioTensor

Shift pitch by semitones and restore the original sample count.

View implementation

time_stretch

function
time_stretch(tensor: AudioTensor, rate: float) → AudioTensor

Change duration by a rate factor. A rate above one makes audio shorter.

View implementation

estimate_f0

function
estimate_f0(tensor: AudioTensor, frame_duration: float=0.05) → list[float]

Estimate fundamental frequency per complete frame using autocorrelation; 0.0 represents unvoiced frames.

View implementation

phonotensor.ops.spectral

Multichannel input is averaged to mono. STFT produces complex frames; fft produces magnitudes. Default STFT hop is n_fft // 4. Supported windows: hann, hamming, blackman, bartlett, rectangular, boxcar.

fft

function
fft(tensor: AudioTensor) → FeatureTensor

Return the magnitude of the one-sided FFT as a single feature frame.

View implementation

frequency_axis

function
frequency_axis(tensor_or_rate: AudioTensor | int, n_fft: int | None=None) → np.ndarray

Return real FFT frequency bins in Hz. Supply n_fft when passing an integer sample rate.

View implementation

stft

function
stft(tensor: AudioTensor, n_fft: int=2048, hop_length: int | None=None, window: str='hann') → FeatureTensor

Compute complex short-time Fourier frames, padding the tail as needed.

View implementation

istft

function
istft(feature: FeatureTensor, n_fft: int | None=None, hop_length: int | None=None, window: str='hann', length: int | None=None) → AudioTensor

Reconstruct mono audio from complex STFT frames by overlap-add. Optional length trims the result.

View implementation

magnitude

function
magnitude(feature: FeatureTensor) → FeatureTensor

Extract magnitudes from complex features; real input is returned unchanged.

View implementation

phase

function
phase(feature: FeatureTensor) → FeatureTensor

Extract angles in radians; requires complex features.

View implementation

phonotensor.ops.transform

Return transformed audio. gain uses decibels; fade durations are seconds. normalize scales the global peak. Use positive durations of at least one sample for fades.

normalize

function
normalize(tensor: AudioTensor, peak_level: float=1.0) → AudioTensor

Scale samples so the global absolute peak equals peak_level. Silent input returns a copy.

View implementation

resample

function
resample(tensor: AudioTensor, target_rate: int) → AudioTensor

Change sample rate using SciPy Fourier resampling.

View implementation

fade_in

function
fade_in(tensor: AudioTensor, duration: float) → AudioTensor

Apply a linear ramp from zero to one at the start.

View implementation

fade_out

function
fade_out(tensor: AudioTensor, duration: float) → AudioTensor

Apply a linear ramp from one to zero at the end.

View implementation

gain

function
gain(tensor: AudioTensor, db: float) → AudioTensor

Apply an amplitude gain of 10 ** (db / 20).

View implementation

clip

function
clip(tensor: AudioTensor, min_val: float=-1.0, max_val: float=1.0) → AudioTensor

Limit samples to the supplied minimum and maximum.

View implementation

phonotensor.permissions

Best-effort file and audio permission checks. Successful preflight checks do not guarantee a device can open; OS and backend errors can still propagate.

phonotensor.platform

Platform detection and backend selection. PortAudio is the implemented backend; other enum names are not separate implemented engines.