audio_samples 0.10.1

A typed audio processing library for Rust that treats audio as a first-class, invariant-preserving object rather than an unstructured numeric buffer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<div align="center">

# AudioSamples

## Fast, simple, and expressive audio in Rust

<img src="logo.png" title="AudioSamples Logo -- Ferrous' Mustachioed Cousin From East Berlin, Eisenhaltig" width="200"/>

[![Crates.io][crate-img]][crate] [![Docs.rs][docs-img]][docs] [![License: MIT][license-img]][license]
</div>

A typed audio processing library for Rust that treats audio as a
first-class, invariant-preserving object rather than an unstructured
numeric buffer.

AudioSamples provides explicit sample-format semantics, safe and
transparent conversions between integer and floating-point
representations, and a coherent API for constructing, transforming,
and analysing audio data without relying on convention or implicit
assumptions.

---
A typed audio processing library for Rust that treats audio as a
first-class, invariant-preserving object rather than an unstructured
numeric buffer.

AudioSamples provides explicit sample-format semantics, safe and
transparent conversions between integer and floating-point
representations, and a coherent API for constructing, transforming,
and analysing audio data without relying on convention or implicit
assumptions.

---

## Overview

Most audio libraries expose samples as raw numeric buffers. In Python,
audio is typically represented as a NumPy array whose `dtype` is
explicit, but whose meaning is not: sample rate, channel layout,
amplitude range, memory interleaving, and PCM versus floating-point
semantics are tracked externally, if at all. In Rust, the situation is
reversed but not resolved. Libraries provide fast and safe low-level
primitives, yet users are still responsible for managing raw buffers,
writing ad hoc conversion code, and manually preserving invariants
across crates.

AudioSamples is designed to close this gap by providing a strongly
typed audio representation that makes audio semantics explicit and
enforced by construction. Sample format, numeric domain, channel
structure, and layout are encoded in the type system, and all
operations preserve or explicitly update these invariants.

The result is an API that supports both exploratory workflows and
reliable system-level use, without requiring users to remember hidden
conventions or reimplement common audio logic.

AudioSamples is the core data and processing layer of the broader
AudioRs ecosystem. It defines the canonical audio object and the
operations that act upon it.

Other crates in the ecosystem build on this foundation:

- `audio_io` for decoding and encoding audio containers into typed
  audio objects
- `audio_playback` for device-level output
- `audio_python` for Python bindings, enabling AudioSamples to act as a
  type-safe backend for Python workflows
- `html_view` for lightweight visualisation and inspection, generating
  self-contained HTML outputs suitable for analysis and reporting

By separating representation from I/O, playback, and visualisation,
AudioRs remains modular while enforcing a single, consistent audio
model throughout the stack.

---

## Why Use audio_samples?

AudioSamples exists to make audio semantics explicit and enforceable.

In many audio libraries, audio data is represented as a numeric buffer
with metadata tracked separately or implicitly. Sample rate, channel
layout, amplitude domain, and sample representation often exist outside
the type system and are maintained by convention. As a result,
mismatches between representations can propagate silently through
pipelines, particularly when converting between integer PCM and
floating-point formats or combining signals from different sources.

AudioSamples addresses this by treating audio as a structured object.
An `AudioSamples<'a, T>` value couples sample data with its sample rate
and channel layout, and operations on audio explicitly preserve or
update these invariants. Conversions between sample formats are defined
in terms of semantic transformations rather than raw casts, ensuring
that changes in numerical representation are intentional and
well-defined.

This design supports workflows where correctness matters: research
pipelines, long-lived systems code, and multi-stage audio processing
where buffers pass through several components. Rather than relying on
discipline or external documentation, AudioSamples encodes audio
assumptions directly in the API.

---
Most audio libraries expose samples as raw numeric buffers. In Python,
audio is typically represented as a NumPy array whose `dtype` is
explicit, but whose meaning is not: sample rate, channel layout,
amplitude range, memory interleaving, and PCM versus floating-point
semantics are tracked externally, if at all. In Rust, the situation is
reversed but not resolved. Libraries provide fast and safe low-level
primitives, yet users are still responsible for managing raw buffers,
writing ad hoc conversion code, and manually preserving invariants
across crates.

AudioSamples is designed to close this gap by providing a strongly
typed audio representation that makes audio semantics explicit and
enforced by construction. Sample format, numeric domain, channel
structure, and layout are encoded in the type system, and all
operations preserve or explicitly update these invariants.

The result is an API that supports both exploratory workflows and
reliable system-level use, without requiring users to remember hidden
conventions or reimplement common audio logic.

AudioSamples is the core data and processing layer of the broader
AudioRs ecosystem. It defines the canonical audio object and the
operations that act upon it.

Other crates in the ecosystem build on this foundation:

- `audio_io` for decoding and encoding audio containers into typed
  audio objects
- `audio_playback` for device-level output
- `audio_python` for Python bindings, enabling AudioSamples to act as a
  type-safe backend for Python workflows
- `html_view` for lightweight visualisation and inspection, generating
  self-contained HTML outputs suitable for analysis and reporting

By separating representation from I/O, playback, and visualisation,
AudioRs remains modular while enforcing a single, consistent audio
model throughout the stack.

---

## Why Use audio_samples?

AudioSamples exists to make audio semantics explicit and enforceable.

In many audio libraries, audio data is represented as a numeric buffer
with metadata tracked separately or implicitly. Sample rate, channel
layout, amplitude domain, and sample representation often exist outside
the type system and are maintained by convention. As a result,
mismatches between representations can propagate silently through
pipelines, particularly when converting between integer PCM and
floating-point formats or combining signals from different sources.

AudioSamples addresses this by treating audio as a structured object.
An `AudioSamples<'a, T>` value couples sample data with its sample rate
and channel layout, and operations on audio explicitly preserve or
update these invariants. Conversions between sample formats are defined
in terms of semantic transformations rather than raw casts, ensuring
that changes in numerical representation are intentional and
well-defined.

This design supports workflows where correctness matters: research
pipelines, long-lived systems code, and multi-stage audio processing
where buffers pass through several components. Rather than relying on
discipline or external documentation, AudioSamples encodes audio
assumptions directly in the API.

---

## Installation

```bash
cargo add audio_samples
```

See the [Features](#features) for more details.

---
See the [Features](#features) for more details.

---

## Quick Start

### Generating and mixing signals

This example generates a sine wave in a target sample format, converts
it to floating-point samples, and mixes it with a second signal.

```rust
use audio_samples::{
    AudioProcessing, AudioTypeConversion, cosine_wave, operations::types::NormalizationMethod,
    sine_wave,
};
use std::time::Duration;

fn main() {
    let sample_rate = 44_100;
    let duration = Duration::from_secs_f64(1.0);
    let frequency = 440.0;
    let amplitude = 0.5;

    // Generate a sine wave with i16 output samples.
    // The waveform is computed in f32 and converted into i16.
    let pcm_sine = sine_wave::<i16, f32>(frequency, duration, sample_rate, amplitude);

    // Convert to floating-point representation
    let float_sine = pcm_sine.to_format::<f32>();

    // Generate a second signal directly as floating-point samples
    let cosine = cosine_wave::<f32, f32>(frequency / 2.0, duration, sample_rate, amplitude);

    // Mix the two signals
    let mixed = (float_sine + cosine).normalize(-1.0, 1.0, NormalizationMethod::MinMax);
}
```

---

### Spectral transforms and analysis

AudioSamples supports spectral and time–frequency transforms via the
`AudioTransforms` trait, enabled by the `spectral-analysis` feature.
These operations produce standard frequency-domain and
time–frequency representations used in audio analysis and research.

Enable the feature:

```bash
cargo add audio_samples --features spectral-analysis
```

#### Example: STFT, spectrogram, and MFCC computation
use audio_samples::{
    AudioProcessing, AudioTypeConversion, cosine_wave, operations::types::NormalizationMethod,
    sine_wave,
};
use std::time::Duration;

fn main() {
    let sample_rate = 44_100;
    let duration = Duration::from_secs_f64(1.0);
    let frequency = 440.0;
    let amplitude = 0.5;

    // Generate a sine wave with i16 output samples.
    // The waveform is computed in f32 and converted into i16.
    let pcm_sine = sine_wave::<i16, f32>(frequency, duration, sample_rate, amplitude);

    // Convert to floating-point representation
    let float_sine = pcm_sine.to_format::<f32>();

    // Generate a second signal directly as floating-point samples
    let cosine = cosine_wave::<f32, f32>(frequency / 2.0, duration, sample_rate, amplitude);

    // Mix the two signals
    let mixed = (float_sine + cosine).normalize(-1.0, 1.0, NormalizationMethod::MinMax);
}
```

---

### Spectral transforms and analysis

AudioSamples supports spectral and time–frequency transforms via the
`AudioTransforms` trait, enabled by the `spectral-analysis` feature.
These operations produce standard frequency-domain and
time–frequency representations used in audio analysis and research.

Enable the feature:

```bash
cargo add audio_samples --features spectral-analysis
```

#### Example: STFT, spectrogram, and MFCC computation

```rust
use audio_samples::{
    AudioTransforms,
    operations::types::{SpectrogramScale, WindowType},
    sine_wave,
};
use std::time::Duration;

fn main() -> audio_samples::AudioSampleResult<()> {
    let sample_rate = 44_100;
    let duration = Duration::from_secs_f64(2.0);

    let audio = sine_wave::<f32, f32>(220.0, duration, sample_rate, 0.8);

    let window_size = 2048;
    let hop_size = 512;

    let window = WindowType::<f32>::Hanning;

    let _stft = audio.stft::<f32>(window_size, hop_size, window)?;

    let _spectrogram = audio.spectrogram::<f32>(
        window_size,
        hop_size,
        WindowType::<f32>::Hanning,
        SpectrogramScale::Log,
        true,
    )?;

    let _mfcc = audio.mfcc::<f32>(13, 40, 80.0, (sample_rate as f32) / 2.0)?;

    Ok(())
use audio_samples::{
    AudioTransforms,
    operations::types::{SpectrogramScale, WindowType},
    sine_wave,
};
use std::time::Duration;

fn main() -> audio_samples::AudioSampleResult<()> {
    let sample_rate = 44_100;
    let duration = Duration::from_secs_f64(2.0);

    let audio = sine_wave::<f32, f32>(220.0, duration, sample_rate, 0.8);

    let window_size = 2048;
    let hop_size = 512;

    let window = WindowType::<f32>::Hanning;

    let _stft = audio.stft::<f32>(window_size, hop_size, window)?;

    let _spectrogram = audio.spectrogram::<f32>(
        window_size,
        hop_size,
        WindowType::<f32>::Hanning,
        SpectrogramScale::Log,
        true,
    )?;

    let _mfcc = audio.mfcc::<f32>(13, 40, 80.0, (sample_rate as f32) / 2.0)?;

    Ok(())
}
```

---

## <a name="features">Features</a>

### Default features

- `statistics`
- `processing`
- `editing`
- `channels`

### Major functionality groups

- `fft`
- `resampling`
- `serialization`
- `plotting`

### Transform and analysis features

- `spectral-analysis`
- `beat-detection` (requires `spectral-analysis`)

### Plotting sub-features

- `static-plots` (PNG output)

### Performance features

- `parallel-processing`
- `simd` (nightly only)
- `mkl`
- `fixed-size-audio`

### Utility features

- `formatting`
- `random-generation`
- `utilities-full`

---
---

## <a name="features">Features</a>

### Default features

- `statistics`
- `processing`
- `editing`
- `channels`

### Major functionality groups

- `fft`
- `resampling`
- `serialization`
- `plotting`

### Transform and analysis features

- `spectral-analysis`
- `beat-detection` (requires `spectral-analysis`)

### Plotting sub-features

- `static-plots` (PNG output)

### Performance features

- `parallel-processing`
- `simd` (nightly only)
- `mkl`
- `fixed-size-audio`

### Utility features

- `formatting`
- `random-generation`
- `utilities-full`

---

## Documentation

Full API documentation is available at
[https://docs.rs/audio_samples](https://docs.rs/audio_samples)

---

## Examples

A range of examples is included in the repository.

Additional demos include:

- DTMF encoder and decoder
- Basic synthesis examples
- Audio inspection utilities

More advanced I/O and playback examples are provided in the companion
crates.

---

## AudioRs — Companion Crates

### [`audio_io`]https://github.com/jmg049/audio_io

Audio decoding and encoding into typed audio objects.

### [`audio_playback`]https://github.com/jmg049/audio_playback

Device-level playback built on AudioSamples.

### [`audio_python`]https://github.com/jmg049/audio_python

Python bindings exposing AudioSamples, AudioIO and AudioPlayback.

### [`html_view`]https://github.com/jmg049/HTMLView

A lightweight, cross-platform HTML viewer for Rust.

`html_view` provides a minimal, ergonomic API for rendering HTML content in a native window, similar in spirit to `matplotlib.pyplot.show()` for visualisation rather than UI development.

### [`dtmf_tones`]https://github.com/jmg049/dtmf_tones

A zero-heap, `no_std` friendly, **const-first** implementation of the standard DTMF (Dual-Tone Multi-Frequency) keypad used in telephony systems.  
This crate provides compile-time safe mappings between keypad keys and their canonical low/high frequencies, along with **runtime helpers** for practical audio processing.

### [`i24`]https://github.com/jmg049/i24

i24 provides a 24-bit signed integer type for Rust, filling the gap between i16 and i32. This type is particularly useful in audio processing, certain embedded systems, and other scenarios where 24-bit precision is required but 32 bits would be excessive

---

## License

MIT License

---

---

## Contributing

Contributions are welcome. Please submit a pull request and see
[CONTRIBUTING.md](CONTRIBUTING.md) for guidance.
Contributions are welcome. Please submit a pull request and see
[CONTRIBUTING.md](CONTRIBUTING.md) for guidance.

[crate]: https://crates.io/crates/audio_samples  
[crate-img]: https://img.shields.io/crates/v/audio_samples?style=for-the-badge&color=009E73&label=crates.io

[docs]: https://docs.rs/audio_samples  
[docs-img]: https://img.shields.io/badge/docs.rs-online-009E73?style=for-the-badge&labelColor=gray

[license-img]: https://img.shields.io/crates/l/audio_samples?style=for-the-badge&label=license&labelColor=gray  
[license]: https://github.com/jmg049/audio_samples/blob/main/LICENSE