Browse documentation
aner.audio

Aner Audio

Decode recordings, capture bounded analysis blocks, preserve sample clocks and connect native audio to tensors, persistent DSP and waveform plots.

ImplementedAner 0.1.0 or newer

aner.audio provides native PCM values, recorded file analysis, bounded block sources, sample rate conversion and WAV recording. It connects to signal analysis, speech analysis, shared audio/video sessions and ordinary CPU tensors. The complete callable reference is MEDIA_ANALYSIS_API.md.

aner
import aner.audio
import aner.tensor

let clip = audio.tone(seconds: 0.25, rate: 48000, channels: 2,
                      frequency: 440.0, amplitude: 0.25)
print(clip.frames())
print(clip.duration())
print(clip.sample(0, channel: 1))
let samples = clip.tensor()

An audio frame contains one sample for every channel at one sampling instant. A stereo clip with 48000 frames therefore contains 96000 interleaved samples. AudioClip is immutable shared Float32 storage. Its samples must be finite; nominal full scale is 1.0, but analysis values are not silently clipped. Channel numbers are zero based, and an unknown multichannel layout remains distinguishable from a known speaker layout.

clip.tensor() copies into an owned CPU Float32 tensor with shape [frames, channels]. audio.from_tensor(samples, rate: 48000, channels: 2) copies finite CPU samples back into an immutable clip. Rank one input is accepted for mono. Device transfer, model specific normalization and feature layouts are explicit operations.

Files and reusable blocks

audio.load(path, memory_mb: 256, max_seconds: 3600.0) collects one bounded recording into a clip. audio.file(path, block_frames: 1024, queue_blocks: 16, memory_mb: 256) reads incrementally. Use the incremental source for longer analyses instead of retaining every block.

aner
import aner.audio

let source = audio.synthetic(frames: 4800, rate: 48000,
                             block_frames: 480, queue_blocks: 2)
let block = audio.block_slot()
while source.read_into(block) == "ready" {
    print(block.first_sample())
    print(block.frames())
}
print(source.delivered())
source.close()

read_into returns a scalar status: ready, timeout, end, cancelled, closed or failed. A nonready result invalidates the block while retaining its reusable allocation. Read source.error() after failed. The read timeout is a caller wait budget; the worker can continue acquiring data after timeout. Native read/open deadlines are cooperative backend limits rather than a hard device response guarantee.

Copies of a block handle alias its mutable state. block.freeze() creates an independent immutable AudioClip before reuse. Freezing and tensor export allocate bounded copies; retaining every result still grows the caller's total memory use. Sources, resamplers and writers are mutable handles whose aliases refer to the same object.

Offline sources apply backpressure and preserve block order. Live capture overload fails explicitly instead of silently removing part of a recording. Native C++ also offers an opt in drop policy that marks the next delivered block with gap_before and a known lost_frames count. Missing samples are not inferred to be silence. Decoder timestamps can reveal discontinuities, but device/transport losses that the backend does not expose cannot be counted reliably.

Sample time and presentation time

Each initialized value carries sample rate, channels, frame count, source/session IDs, first sample index, sequence, PTS availability, timestamp provenance, receipt time and gap metadata. received_ns uses the host monotonic clock and is not a microphone exposure timestamp. A standalone synthetic clip has a sample derived clock; a file can have media timestamps; an A/V session uses a shared presentation clock.

Source/session identities are allocated across audio, video and shared sessions within one process and stay within Int64. They identify a source lifetime, not a persistent hardware address or synchronization guarantee. Zero identifies an anonymous in memory clip without an acquired source. Shared session audio/video events deliberately carry the same identity.

Sample index time is first_sample / rate. It can differ from presentation time. For example, the first audio block in a media session can have first_sample == 0 and pts_ns == 250000000 because audio begins 250 ms after video. value.time(frame: 0) gives the first frame's presentation seconds when PTS is known, falling back to source sample seconds otherwise.

Signal features and speech intervals use source sample seconds. To compare them with video, retain a matching audio anchor and call anchor.timeline(feature_or_speech_seconds). This applies:

text
presentation seconds = anchor.pts_ns / 1e9
                     + source-sample seconds
                     - anchor.first_sample / anchor.rate

The conversion requires known PTS and the same source/session and sampling clock. It cannot establish synchronization between unrelated microphones or independently opened recordings. Freeze an anchor before a block is reused.

Resampling and channel selection

clip.channel(index) explicitly selects one channel. clip.resample(rate: 16000, channels: 1) performs bounded antialiased conversion with installed libswresample. Mono conversion uses an explicit equal channel average. Zero output channels preserves the input count. Choosing a microphone channel can be more appropriate than averaging a multichannel recording whose channels contain different sources.

For a stream, create audio.resampler(in_rate: 48000, in_channels: 2, out_rate: 16000, out_channels: 1) once. Process contiguous immutable blocks, then flush delayed samples once at EOF. Reset after an intentional discontinuity. Recreating the converter for every block loses filter history and changes boundary samples. Resampling propagates source/session metadata and maps sample positions to the output rate; it does not prove clock synchronization between USB devices.

Without FFmpeg, identity conversion and same rate arithmetic channel conversion remain available. Changing sample rate requires the optional backend. Multiple physical devices still need clock selection, drift measurement and, where appropriate, adaptive rate correction; those device synchronization controls are outside this analysis capture increment.

Recording and limits

audio.write_wav(path, clip, format: "float32") creates a new WAV exclusively. audio.record(path, rate: 48000, channels: 1, format: "float32") writes incrementally through writer.write(block) or writer.write(clip). Close explicitly to finalize RIFF sizes. Existing destinations and symlinks are refused. Float32 preserves finite samples; selecting pcm16 explicitly clips to full scale and quantizes. WAV cannot represent arbitrary timestamp gaps: the writer rejects flagged gaps and discontinuous known source indices instead of hiding them. Split the recording or explicitly construct replacement samples with an appropriate provenance policy.

The RIFF writer stops before the 4 GiB container limit; RF64 and synchronized A/V mux recording are future work. An interrupted process can leave an incomplete file whose header has not been finalized.

Default native clip limits are 256 MiB, 100 million frames and 3600 seconds per collected value. Rates are 1..384000 Hz and channel counts 1..64; backend codecs/devices can support fewer modes. Source blocks are at most 65536 frames. The source language queue is bounded by both queue_blocks and at most 4 MiB of PCM payload, further capped by memory_mb. Caller slots, immutable results, decoder buffers, resampler workspace and model state are additional allocations; the queue budget is not a whole process memory ceiling.

Backend and capture qualification

audio.available() reports installed FFmpeg decoding/resampling support. Synthetic PCM, native RIFF PCM8/16/24/32 and Float32 WAV reading, and WAV writing do not require it. Other recording/container codecs and remote input depend on the installed FFmpeg build.

audio.microphone() uses an analysis worker with FFmpeg's platform input adapter: AVFoundation on macOS, ALSA on Linux, DirectShow on Windows. macOS default maps to :0; Linux retains the backend's default; Windows requires an explicit audio=Device Name. Device permissions, supported formats and hot unplug behavior depend on the host. This interface does not expose a low latency duplex callback, playback, echo cancellation or a conversation engine. No hardware microphone was opened by the deterministic module tests.

audio.stream accepts clean unauthenticated HTTP(S)/RTSP(S) endpoints. Userinfo, query parameters and fragments are rejected in this increment. TLS verification is enabled for encrypted transports; selecting HTTP/RTSP does not add encryption. There is no authenticated remote audio header adapter yet. Native code uses linked libraries, sanitized diagnostics and bounded deadlines; it does not launch FFmpeg or another language runtime subprocesses.

Examples: basic clips, streaming blocks, stateful resampling.

Waveforms and model inputs

aner
import aner.audio
import aner.plot

let clip = audio.tone(seconds: 0.1, frequency: 440.0)
let waveform = audio.waveform(clip, channel: 0, max_points: 2048)
waveform.title("Native audio waveform").save("waveform.svg")

The Chart is an immutable native snapshot. Its horizontal axis uses source sample seconds and its vertical axis uses digital amplitude. A bounded min/max envelope keeps bucket extrema in sample order, preserving short transients. The preview does not retain every sample or establish calibrated sound pressure. Use show() for native notebook display and save to a new .svg or .html path for a portable chart; existing files are not overwritten.

Use clip.tensor() for owned CPU Float32 [frames, channels] input. Signal supplies frequency/feature plots, explicit CNN [1,C,F,T] and recurrent [1,T,C*F] layouts, summary features for ML, and complete examples connecting them to NN. Match the training recipe and make datatype/device transfer explicit before model execution. Speech carries timed transcripts into NLP; Media preserves the presentation clock relationship to video.

See the complete callable index for the native module and method name catalogue.

Aner documentation · Reference and guides