AudioSamples

Struct AudioSamples 

Source
pub struct AudioSamples<'a, T: AudioSample> {
    pub data: AudioData<'a, T>,
    pub sample_rate: NonZeroU32,
    pub layout: ChannelLayout,
}
Expand description

Represents homogeneous audio samples with associated metadata.

Primary container for audio data combining raw sample values with essential metadata including sample rate, channel layout, and type information. Supports both mono and multi-channel audio with unified interface.

§Fields

  • data: Audio sample data in mono or multi-channel format
  • sample_rate: Sampling frequency in Hz
  • layout: Channel organization (interleaved or non-interleaved)

§Examples

use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;

let mono_audio = AudioSamples::new_mono(array![0.1f32, 0.2, 0.3], sample_rate!(44100));
assert_eq!(mono_audio.num_channels(), 1);

let stereo_data = array![[0.1f32, 0.2], [0.3f32, 0.4]];
let stereo_audio = AudioSamples::new_multi_channel(stereo_data, sample_rate!(48000));
assert_eq!(stereo_audio.num_channels(), 2);

§Invariants

The following properties are guaranteed by construction and cannot be violated:

  • sample_rate is always > 0 (stored as NonZeroU32)
  • num_channels() is always ≥ 1 (mono has 1 channel, multi has ≥ 1 rows)
  • samples_per_channel() is always ≥ 1 (empty audio is not allowed)

These invariants eliminate the need for runtime validation in downstream code.

Fields§

§data: AudioData<'a, T>

The audio sample data.

§sample_rate: NonZeroU32

Sample rate in Hz (guaranteed non-zero).

§layout: ChannelLayout

Channel layout metadata.

Note: multi-channel sample data stored in AudioData::Multi is represented as a 2D array with shape (channels, samples_per_channel) (planar). This field records how the samples should be interpreted/serialized (e.g. when converting to/from an interleaved Vec<T>).

Implementations§

Source§

impl<'a, T: AudioSample> AudioSamples<'a, T>

Source

pub fn apply_with_error<F>(&mut self, f: F) -> AudioSampleResult<()>
where F: Fn(T) -> AudioSampleResult<T>,

Applies a fallible function to all samples in the audio data. This is a helper method for operations that can fail.

§Examples
// Apply a conversion that might fail
audio.apply_with_error(|sample| {
    if sample > max_value {
        Err(AudioSampleError::Parameter(/* error */))
    } else {
        Ok(sample * 2.0)
    }
})?;
Source

pub fn try_fold<F, Acc>(&mut self, acc: Acc, f: F) -> AudioSampleResult<Acc>
where F: FnMut(&mut Acc, T) -> AudioSampleResult<T>,

Applies a fallible function that uses an accumulator pattern. Useful for operations that need to maintain state across samples.

§Examples
let mut state = 0.0;
audio.try_fold(|acc, sample| {
    *acc += sample.abs();
    if *acc > threshold {
        Err(AudioSampleError::Parameter(/* error */))
    } else {
        Ok(sample)
    }
})?;
Source§

impl<'a, T: AudioSample> AudioSamples<'a, T>

Source

pub fn frames(&'a self) -> FrameIterator<'a, T>

Returns an iterator over frames (one sample from each channel).

§Returns

A FrameIterator yielding borrowed frame views.

§Panics

Does not panic.

Source

pub fn channels<'iter>(&'iter self) -> ChannelIterator<'iter, 'a, T>

Returns an iterator over complete channels.

§Returns

A ChannelIterator yielding owned AudioSamples values (one per channel).

§Panics

Does not panic.

Source

pub fn windows( &'a self, window_size: usize, hop_size: usize, ) -> WindowIterator<'a, T>

Returns an iterator over windows of audio data.

The default padding mode is PaddingMode::Zero.

§Inputs
  • window_size: size of each window in samples (per channel)
  • hop_size: number of samples to advance between windows
§Returns

A WindowIterator yielding owned windows.

§Panics

Does not panic. If window_size == 0 or hop_size == 0, the iterator yields no items.

Source

pub fn frames_mut(&'a mut self) -> FrameIteratorMut<'a, T>

Returns a mutable iterator over frames (one sample from each channel).

§Panics

Panics if the underlying multi-channel storage is not contiguous in memory.

Source

pub fn channels_mut(&'a mut self) -> ChannelIteratorMut<'a, T>

Returns a mutable iterator over complete channels.

§Panics

Panics if the underlying multi-channel storage is not contiguous in memory.

Source

pub fn windows_mut( &'a mut self, window_size: usize, hop_size: usize, ) -> WindowIteratorMut<'a, T>

Returns a mutable iterator over non-overlapping windows of audio data.

§Panics
  • Panics if hop_size < window_size and more than one window would be yielded.
  • Panics if the underlying multi-channel storage is not contiguous in memory.

If window_size == 0 or hop_size == 0, the iterator yields no items.

Source

pub fn apply_to_frames<F>(&mut self, f: F)
where F: FnMut(usize, &mut [T]),

Applies a function to each frame without borrowing issues.

For mono audio, the callback receives a mutable slice of length 1.

For multi-channel audio, the callback receives a temporary buffer containing exactly one sample per channel. The buffer is ordered by channel index and is copied back into the underlying audio after the callback returns.

§Inputs
  • f(frame_index, frame_samples)
§Returns

()

§Panics

Does not panic.

Source

pub fn try_apply_to_channel_data<F>(&mut self, f: F) -> AudioSampleResult<()>
where F: FnMut(usize, &mut [T]),

Applies a function to each channel’s raw data without borrowing issues.

§Inputs
  • f(channel_index, channel_samples)
§Returns

Ok(()) on success.

§Errors

Returns AudioSampleError::Layout if the underlying storage is not contiguous.

Source

pub fn apply_to_channel_data<F>(&mut self, f: F)
where F: FnMut(usize, &mut [T]),

Applies a function to each channel’s raw data without borrowing issues.

This is the infallible counterpart to AudioSamples::try_apply_to_channel_data.

§Panics

Panics if the underlying storage is not contiguous in memory.

Source

pub fn apply_to_windows<F>(&mut self, window_size: usize, hop_size: usize, f: F)
where F: FnMut(usize, &mut [T]),

Applies a function to each window without borrowing issues.

For mono audio, the callback receives a mutable slice into the underlying buffer.

For multi-channel audio, the callback receives a temporary interleaved buffer of length window_size * num_channels that is copied back after the callback returns.

§Inputs
  • window_size: size of each window in samples (per channel)
  • hop_size: number of samples to advance between windows
  • f(window_index, window_samples)
§Panics

Does not panic. If window_size == 0 or the audio is empty, this method returns immediately.

Source§

impl<T: AudioSample> AudioSamples<'static, T>

Source

pub fn from_owned(data: AudioData<'_, T>, sample_rate: NonZeroU32) -> Self

Creates AudioSamples from owned data.

Source

pub fn into_data(self) -> AudioData<'static, T>

Consumes self and returns the underlying AudioData

Source

pub fn into_array1(self) -> Option<Array1<T>>

Consumes self and returns the underlying mono Array1 if applicable

Source

pub fn into_array2(self) -> Option<Array2<T>>

Consumes self and returns the underlying multi-channel Array2 if applicable

Source§

impl<'a, T: AudioSample> AudioSamples<'a, T>

Source

pub const fn new(data: AudioData<'a, T>, sample_rate: NonZeroU32) -> Self

Creates a new AudioSamples with the given data and sample rate.

This is a low-level constructor. Prefer new_mono or new_multi_channel for most use cases.

Source

pub const fn from_borrowed( data: AudioData<'a, T>, sample_rate: NonZeroU32, ) -> Self

Creates AudioSamples from borrowed data.

Source

pub const fn from_borrowed_with_layout( data: AudioData<'a, T>, sample_rate: NonZeroU32, layout: ChannelLayout, ) -> Self

Creates AudioSamples from borrowed data with specified channel layout.

Source

pub fn convert_to<O: AudioSample>(&self) -> AudioSamples<'static, O>
where T: ConvertTo<O>,

Convert audio samples to another sample type.

Source

pub fn to_interleaved_vec(&self) -> Vec<T>

Convert the AudioSamples struct into a vector of samples in interleaved format.

Source

pub fn new_mono<'b>( data: Array1<T>, sample_rate: NonZeroU32, ) -> AudioSamples<'b, T>

Creates a new mono AudioSamples that owns its data.

§Arguments
  • data - 1D array containing the audio samples
  • sample_rate - Sample rate in Hz
§Returns

A new mono AudioSamples instance that owns the provided data.

§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;

let data = array![1.0f32, -1.0, 0.5, -0.5];
let audio = AudioSamples::new_mono(data, sample_rate!(44100));
assert_eq!(audio.num_channels(), 1);
assert_eq!(audio.sample_rate().get(), 44100);

Creates a new mono AudioSamples with the given data and sample rate.

§Panics
  • If data is empty
Source

pub fn try_new_mono<'b>( data: Array1<T>, sample_rate: u32, ) -> AudioSampleResult<AudioSamples<'b, T>>

Creates a new mono AudioSamples that owns its data, returning an error on invalid input.

This is the fallible version of new_mono. Use this when you want to handle validation errors gracefully instead of panicking.

§Arguments
  • data - 1D array containing the audio samples
  • sample_rate - Sample rate in Hz (must be non-zero)
§Returns

Ok(AudioSamples) on success, or an error if:

  • data is empty
  • sample_rate is zero
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Valid input
let data = array![1.0f32, -1.0, 0.5, -0.5];
let audio = AudioSamples::try_new_mono(data, 44100).unwrap();
assert_eq!(audio.num_channels(), 1);

// Invalid input (empty array)
let empty = ndarray::Array1::<f32>::zeros(0);
assert!(AudioSamples::try_new_mono(empty, 44100).is_err());

// Invalid input (zero sample rate)
let data = array![1.0f32, -1.0];
assert!(AudioSamples::try_new_mono(data, 0).is_err());
Source

pub fn new_multi_channel<'b>( data: Array2<T>, sample_rate: NonZeroU32, ) -> AudioSamples<'b, T>

Creates a new multi-channel AudioSamples with the given data and sample rate.

§Arguments
  • data - 2D array where each row represents a channel and each column a sample
  • sample_rate - Sample rate in Hz
§Returns

A new multi-channel AudioSamples instance that owns the provided data.

§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;

let data = array![[1.0f32, -1.0], [0.5, -0.5]]; // 2 channels, 2 samples each
let audio = AudioSamples::new_multi_channel(data, sample_rate!(44100));
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 2);

Creates a new multi-channel AudioSamples with the given data and sample rate.

§Panics
  • If data is empty (has zero samples per channel)
Source

pub fn try_new_multi_channel<'b>( data: Array2<T>, sample_rate: u32, ) -> AudioSampleResult<AudioSamples<'b, T>>

Creates a new multi-channel AudioSamples, returning an error on invalid input.

This is the fallible version of new_multi_channel. Use this when you want to handle validation errors gracefully instead of panicking.

§Arguments
  • data - 2D array where each row represents a channel and each column a sample
  • sample_rate - Sample rate in Hz (must be non-zero)
§Returns

Ok(AudioSamples) on success, or an error if:

  • data has zero samples per channel (zero columns)
  • sample_rate is zero
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Valid input
let data = array![[1.0f32, -1.0], [0.5, -0.5]]; // 2 channels, 2 samples each
let audio = AudioSamples::try_new_multi_channel(data, 44100).unwrap();
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 2);

// Invalid input (zero columns)
let empty = ndarray::Array2::<f32>::zeros((2, 0));
assert!(AudioSamples::try_new_multi_channel(empty, 44100).is_err());

// Invalid input (zero sample rate)
let data = array![[1.0f32, -1.0], [0.5, -0.5]];
assert!(AudioSamples::try_new_multi_channel(data, 0).is_err());
Source

pub fn zeros_mono(length: usize, sample_rate: NonZeroU32) -> Self

Creates a new mono AudioSamples filled with zeros.

§Arguments
  • length - Number of samples to create
  • sample_rate - Sample rate in Hz
§Returns

A new mono AudioSamples instance filled with zero values.

§Examples
use audio_samples::AudioSamples;

let audio = AudioSamples::<f32>::zeros_mono(1024, sample_rate!(44100));
assert_eq!(audio.samples_per_channel(), 1024);
assert_eq!(audio.num_channels(), 1);
§Panics
  • If length is 0
Source

pub fn zeros_multi( channels: usize, length: usize, sample_rate: NonZeroU32, ) -> Self

Creates a new multi-channel AudioSamples filled with zeros.

§Arguments
  • channels - Number of channels to create
  • length - Number of samples per channel
  • sample_rate - Sample rate in Hz
§Returns

A new multi-channel AudioSamples instance filled with zero values.

§Examples
use audio_samples::{AudioSamples, sample_rate};

let audio = AudioSamples::<f32>::zeros_multi(2, 1024, sample_rate!(44100));
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 1024);
§Panics
  • If length is 0
Source

pub fn zeros_multi_channel( channels: usize, length: usize, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>

Creates a new multi-channel AudioSamples filled with zeros (static version)

§Panics
  • If length is 0
Source

pub fn ones_mono(length: usize, sample_rate: NonZeroU32) -> Self

Creates a new mono AudioSamples filled with ones

§Panics
  • If length is 0
Source

pub fn ones_multi( channels: usize, length: usize, sample_rate: NonZeroU32, ) -> Self

Creates a new multi-channel AudioSamples filled with ones

§Panics
  • If length is 0
Source

pub fn uniform_mono(length: usize, sample_rate: NonZeroU32, value: T) -> Self

Creates a new mono AudioSamples filled with the specified value

§Panics
  • If length is 0
Source

pub fn uniform_multi( channels: usize, length: usize, sample_rate: NonZeroU32, value: T, ) -> Self

Creates a new multi-channel AudioSamples filled with the specified value

§Panics
  • If length is 0
Source

pub const fn layout_mut(&mut self) -> &mut ChannelLayout

Returns a mutable reference to the channel layout

Source

pub const fn set_layout(&mut self, layout: ChannelLayout)

Sets the channel layout

Source

pub fn info(&self) -> (usize, usize, f64, u32, ChannelLayout)

Returns basic info: (num_channels, samples_per_channel, duration_seconds, sample_rate, layout)

Source

pub const fn sample_rate(&self) -> NonZeroU32

Returns the sample rate in Hz as a NonZeroU32.

This is guaranteed to be non-zero by construction.

§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;

let audio = AudioSamples::new_mono(array![1.0f32, 2.0], sample_rate!(44100));
assert_eq!(audio.sample_rate().get(), 44100);
Source

pub const fn sample_rate_hz(&self) -> u32

Returns the sample rate as a plain u32.

This is a convenience method equivalent to self.sample_rate().get().

Source

pub fn num_channels(&self) -> usize

Returns the number of channels.

This is guaranteed to be ≥ 1 by construction.

Source

pub fn num_channels_nonzero(&self) -> NonZeroUsize

Returns the number of channels as a NonZeroUsize.

This provides a compile-time guarantee that the value is non-zero, eliminating the need for runtime validation in downstream code.

§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;

let audio = AudioSamples::new_mono(array![1.0f32, 2.0], sample_rate!(44100));
let channels = audio.num_channels_nonzero();
assert_eq!(channels.get(), 1);
Source

pub fn samples_per_channel(&self) -> usize

Returns the number of samples per channel.

This is guaranteed to be ≥ 1 by construction (empty audio is not allowed).

Source

pub fn samples_per_channel_nonzero(&self) -> NonZeroUsize

Returns the number of samples per channel as a NonZeroUsize.

This provides a compile-time guarantee that the value is non-zero, eliminating the need for runtime validation in downstream code.

§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;

let audio = AudioSamples::new_mono(array![1.0f32, 2.0, 3.0], sample_rate!(44100));
let samples = audio.samples_per_channel_nonzero();
assert_eq!(samples.get(), 3);
Source

pub fn total_samples_nonzero(&self) -> NonZeroUsize

Returns the total number of samples as a NonZeroUsize.

This is the product of channels × samples_per_channel, both guaranteed non-zero.

Source

pub fn duration_seconds<F: RealFloat>(&self) -> F

Returns the duration in seconds

Source

pub fn total_samples(&self) -> usize

Returns the total number of samples across all channels

Source

pub const fn bytes_per_sample(&self) -> usize

Returns the number of bytes per sample for type T

Source

pub const fn sample_type() -> SampleType

Returns the sample type as a string

Source

pub const fn layout(&self) -> ChannelLayout

Returns the channel layout

Source

pub const fn is_mono(&self) -> bool

Returns true if this is mono audio

Source

pub const fn is_multi_channel(&self) -> bool

Returns true if this is multi-channel audio

Source

pub fn len(&self) -> usize

Returns the total number of samples.

Source

pub fn is_empty(&self) -> bool

Returns true if there are no samples.

Source

pub fn shape(&self) -> &[usize]

Returns the shape of the audio data.

Source

pub fn apply<F>(&mut self, f: F)
where F: Fn(T) -> T,

Applies a function to each sample in the audio data in-place.

This method applies the given function to every sample in the audio data, modifying the samples in-place. The function receives each sample and should return the transformed sample.

§Arguments
  • f - A function that takes a sample and returns a transformed sample
§Returns

Nothing. This method is infallible.

§Example
// Halve the amplitude of all samples
audio.apply(|sample| sample * 0.5);

// Apply a simple distortion
audio.apply(|sample| sample.clamp(-0.8, 0.8));
Source

pub fn apply_to_channels<F>(&mut self, channels: &[usize], f: F)
where F: Fn(T) -> T + Copy,

Apply a function to specific channels.

Source

pub fn map<F>(&self, f: F) -> AudioSamples<'static, T>
where F: Fn(T) -> T,

Maps a function to each sample and returns a new AudioSamples instance.

This is a functional-style version of apply that doesn’t modify the original audio data but returns a new instance with the transformed samples.

§Arguments
  • f - A function that takes a sample and returns a transformed sample
§Returns

A new AudioSamples instance with the transformed samples

§Example
// Create a new audio instance with halved amplitude
let quieter_audio = audio.map(|sample| sample * 0.5);

// Create a new audio instance with clipped samples
let clipped_audio = audio.map(|sample| sample.clamp(-0.8, 0.8));
Source

pub fn map_into<O: AudioSample, F>(&self, f: F) -> AudioSamples<'static, O>
where F: Fn(T) -> O,

Map each sample to a new type using a function. Does not care about in-domain or out-of-domain mapping. i.e. both convert_to and cast_from/into are acceptable.

Source

pub fn apply_with_index<F>(&mut self, f: F)
where F: Fn(usize, T) -> T,

Applies a function to each sample with access to the sample index.

This method is similar to apply but provides the sample index to the function, allowing for position-dependent transformations.

§Arguments
  • f - A function that takes a sample index and sample value, returns transformed sample
§Returns

Nothing. This method is infallible.

§Example
// Apply a fade-in effect
audio.apply_with_index(|index, sample| {
    let fade_samples = 44100; // 1 second fade at 44.1kHz
    let gain = if index < fade_samples {
        index as f32 / fade_samples as f32
    } else {
        1.0
    };
    sample * gain
});
Source

pub fn processing<'b>(&'b mut self) -> ProcessingBuilder<'b, T>
where i16: ConvertTo<T>, I24: ConvertTo<T>, i32: ConvertTo<T>, f32: ConvertTo<T>, f64: ConvertTo<T>, AudioSamples<'a, T>: AudioTypeConversion<'a, T>, 'b: 'a,

Creates a processing builder for fluent operation chaining.

This method provides a builder pattern for chaining multiple audio processing operations together and applying them all at once.

§Example
use audio_samples::{AudioSamples, operations::types::NormalizationMethod};
use ndarray::array;

let mut audio = AudioSamples::new_mono(array![1.0f32, 2.0, 3.0], 44100);
audio.processing()
    .normalize(-1.0, 1.0, NormalizationMethod::Peak)
    .scale(0.5)
    .apply()?;
Source

pub fn slice_samples<R>( &self, sample_range: R, ) -> AudioSampleResult<AudioSamples<'_, T>>
where R: RangeBounds<usize> + Clone,

Slice audio by sample range, keeping all channels.

Creates a new AudioSamples instance containing samples in the specified range.

§Arguments
  • sample_range - Range of samples to extract (e.g., 100..200)
§Returns

A new AudioSamples instance with the sliced samples

§Errors

Returns an error if the range is out of bounds.

Source

pub fn slice_channels<'iter, R>( &'iter self, channel_range: R, ) -> AudioSampleResult<AudioSamples<'static, T>>
where R: RangeBounds<usize> + Clone, 'iter: 'a,

Slice audio by channel range, keeping all samples.

Creates a new AudioSamples instance containing only the specified channels.

§Arguments
  • channel_range - Range of channels to extract (e.g., 0..2 for stereo)
§Returns

A new AudioSamples instance with the sliced channels

§Errors

Returns an error if the range is out of bounds.

Source

pub fn slice_both<CR, SR>( &self, channel_range: CR, sample_range: SR, ) -> AudioSampleResult<AudioSamples<'static, T>>

Slice audio by both channel and sample ranges.

Creates a new AudioSamples instance containing the intersection of the specified channel and sample ranges.

§Arguments
  • channel_range - Range of channels to extract
  • sample_range - Range of samples to extract
§Returns

A new AudioSamples instance with the sliced data

§Errors

Returns an error if either range is out of bounds.

Source

pub fn bytes(&self) -> AudioSampleResult<AudioBytes<'_>>

Returns a contiguous byte view when possible.

Source

pub fn into_bytes(&self) -> Vec<u8>

Convert audio samples to raw bytes, preferring zero-copy when possible.

Source

pub fn as_bytes(&self) -> Vec<u8>

👎Deprecated: use bytes() for borrowed access or into_bytes() for owned bytes

Deprecated: use bytes() or into_bytes() instead.

Source

pub fn total_byte_size(&self) -> usize

Returns the total size in bytes of all audio data.

This is equivalent to self.data.len() * self.bytes_per_sample().

§Examples
use audio_samples::AudioSamples;
use ndarray::array;

let audio = AudioSamples::new_mono(array![1.0f32, 2.0, 3.0], 44100);
assert_eq!(audio.total_byte_size(), 12); // 3 samples × 4 bytes per f32
Source

pub fn apply_windowed<F>( &mut self, window_size: usize, hop_size: usize, func: F, ) -> AudioSampleResult<()>
where F: Fn(&[T], &[T]) -> Vec<T>,

Apply a windowed processing function to the audio data.

This method processes the audio in overlapping windows, applying the provided function to each window and updating the audio data with the results.

§Arguments
  • window_size - Size of each processing window in samples
  • hop_size - Number of samples to advance between windows
  • func - Function called for each window, receiving (current_window, prev_window)
§Returns

Returns Ok(()) on success, or an error if parameters are invalid.

Source

pub fn into_owned<'b>(self) -> AudioSamples<'b, T>

Converts this AudioSamples into an owned version with ’static lifetime.

This method takes ownership of the AudioSamples and ensures all data is owned, allowing it to be moved freely without lifetime constraints.

Source

pub fn replace_data( &mut self, new_data: AudioData<'a, T>, ) -> AudioSampleResult<()>

Replaces the audio data while preserving sample rate and channel layout.

This method allows you to swap out the underlying audio data with new data of the same channel configuration, maintaining the existing sample rate and layout metadata.

§Arguments
  • new_data - The new audio data to replace the current data
§Returns

Returns Ok(()) on success, or an error if the new data has incompatible dimensions.

§Errors
  • Returns ParameterError if the new data has a different number of channels
  • Returns ParameterError if mono/multi-channel layout mismatch occurs
§Examples
use audio_samples::{AudioSamples, AudioData};
use ndarray::array;

// Create initial audio
let initial_data = array![1.0f32, 2.0, 3.0];
let mut audio = AudioSamples::new_mono(initial_data, 44100);

// Replace with new data
let new_data = AudioData::new_mono(array![4.0f32, 5.0, 6.0, 7.0]);
audio.replace_data(new_data)?;

assert_eq!(audio.samples_per_channel(), 4);
assert_eq!(audio.sample_rate(), 44100); // Preserved
Source

pub fn replace_with_mono(&mut self, data: Array1<T>) -> AudioSampleResult<()>

Replaces the audio data with new mono data from an owned Array1.

This is a convenience method for replacing mono audio data while preserving sample rate and layout metadata.

§Arguments
  • data - New mono audio data as an owned Array1
§Returns

Returns Ok(()) on success, or an error if the current audio is not mono.

§Errors
  • Returns ParameterError if the current audio is not mono
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Create initial mono audio
let mut audio = AudioSamples::new_mono(array![1.0f32, 2.0], 44100);

// Replace with new mono data
audio.replace_with_mono(array![3.0f32, 4.0, 5.0])?;

assert_eq!(audio.samples_per_channel(), 3);
assert_eq!(audio.sample_rate(), 44100); // Preserved
Source

pub fn replace_with_multi(&mut self, data: Array2<T>) -> AudioSampleResult<()>

Replaces the audio data with new multi-channel data from an owned Array2.

This is a convenience method for replacing multi-channel audio data while preserving sample rate and layout metadata.

§Arguments
  • data - New multi-channel audio data as an owned Array2 where rows are channels
§Returns

Returns Ok(()) on success, or an error if channel count doesn’t match.

§Errors
  • Returns ParameterError if the current audio is mono
  • Returns ParameterError if the new data has different number of channels
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Create initial stereo audio
let mut audio = AudioSamples::new_multi_channel(
    array![[1.0f32, 2.0], [3.0, 4.0]], 44100
);

// Replace with new stereo data (different length is OK)
audio.replace_with_multi(array![[5.0f32, 6.0, 7.0], [8.0, 9.0, 10.0]])?;

assert_eq!(audio.samples_per_channel(), 3);
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.sample_rate(), 44100); // Preserved
Source

pub fn replace_with_vec(&mut self, samples: Vec<T>) -> AudioSampleResult<()>

Replaces the audio data with new data from a Vec, maintaining current channel layout.

This is a convenience method for replacing audio data with samples from a Vec. The method infers whether to create mono or multi-channel data based on the current AudioSamples configuration.

§Arguments
  • samples - Vector of samples to replace the current audio data
§Returns

Returns Ok(()) on success, or an error if the sample count is incompatible.

§Errors
  • Returns ParameterError if the sample count is not divisible by current channel count
  • Returns ParameterError if the resulting array cannot be created
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Replace mono audio
let mut mono_audio = AudioSamples::new_mono(array![1.0f32, 2.0], 44100);
mono_audio.replace_with_vec(vec![3.0f32, 4.0, 5.0, 6.0])?;
assert_eq!(mono_audio.samples_per_channel(), 4);

// Replace stereo audio (interleaved samples)
let mut stereo_audio = AudioSamples::new_multi_channel(
    array![[1.0f32, 2.0], [3.0, 4.0]], 44100
);
stereo_audio.replace_with_vec(vec![5.0f32, 6.0, 7.0, 8.0, 9.0, 10.0])?;
assert_eq!(stereo_audio.samples_per_channel(), 3); // 6 samples ÷ 2 channels
assert_eq!(stereo_audio.num_channels(), 2);
Source

pub fn replace_with_vec_channels( &mut self, samples: Vec<T>, expected_channels: usize, ) -> AudioSampleResult<()>

Replaces the audio data with new data from a Vec, validating against a specific channel count.

This method is similar to replace_with_vec but validates the sample count against the provided expected_channels parameter rather than the current audio configuration. This is useful when the current audio might be a placeholder or when you want to ensure the data matches a specific channel configuration.

§Arguments
  • samples - Vector of samples to replace the current audio data
  • expected_channels - Expected number of channels for validation
§Returns

Returns Ok(()) on success, or an error if validation fails.

§Errors
  • Returns ParameterError if the sample count is not divisible by expected_channels
  • Returns ParameterError if the current audio doesn’t match expected_channels
  • Returns ParameterError if the resulting array cannot be created
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Create placeholder stereo audio
let mut audio = AudioSamples::new_multi_channel(
    array![[0.0f32, 0.0], [0.0, 0.0]], 44100
);

// Replace with data that must be stereo (2 channels)
let samples = vec![1.0f32, 2.0, 3.0, 4.0]; // 4 samples = 2 samples per channel
audio.replace_with_vec_channels(samples, 2)?;

assert_eq!(audio.samples_per_channel(), 2);
assert_eq!(audio.num_channels(), 2);
Source

pub const fn as_mono(&self) -> Option<&MonoData<'a, T>>

Returns a reference to the underlying mono array if this is mono audio.

§Returns

Some reference to the mono array if this is mono audio, None otherwise.

Source

pub const fn as_multi_channel(&self) -> Option<&MultiData<'a, T>>

Returns a reference to the underlying multi-channel array if this is multi-channel audio.

§Returns

Some reference to the multi-channel array if this is multi-channel audio, None otherwise.

Source

pub const fn as_mono_mut(&mut self) -> Option<&mut MonoData<'a, T>>

Returns a mutable reference to the underlying mono array if this is mono audio.

§Returns

Some mutable reference to the mono array if this is mono audio, None otherwise.

Source

pub const fn as_multi_channel_mut(&mut self) -> Option<&mut MultiData<'a, T>>

Returns a mutable reference to the underlying multi-channel array if this is multi-channel audio.

§Returns

Some mutable reference to the multi-channel array if this is multi-channel audio, None otherwise.

Source

pub fn new_mono_from_slice(slice: &'a [T], sample_rate: NonZeroU32) -> Self

Creates a new mono AudioSamples from a slice.

§Panics
  • If slice is empty
Source

pub fn new_mono_from_mut_slice( slice: &'a mut [T], sample_rate: NonZeroU32, ) -> Self

Creates a new mono AudioSamples from a mutable slice.

§Panics
  • If slice is empty
Source

pub fn new_multi_channel_from_slice( slice: &'a [T], channels: usize, sample_rate: NonZeroU32, ) -> Self

Creates a new multi-channel AudioSamples from a slice.

§Panics
  • If slice is empty
  • If the length of the slice is not divisible by the number of channels.
  • If the slice cannot be reshaped into the desired shape.
Source

pub fn new_multi_channel_from_mut_slice( slice: &'a mut [T], channels: usize, sample_rate: NonZeroU32, ) -> Self

Creates a new multi-channel AudioSamples from a mutable slice.

§Panics
  • If slice is empty
  • If the length of the slice is not divisible by the number of channels.
  • If the slice cannot be reshaped into the desired shape.
Source

pub fn from_vec( vec: Vec<T>, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>

Creates mono AudioSamples from a Vec (owned).

§Panics
  • If vec is empty
§Examples
use audio_samples::{AudioSamples, sample_rate};

let samples = vec![0.1f32, 0.2, 0.3, 0.4];
let audio = AudioSamples::from_vec(samples, sample_rate!(44100));
assert_eq!(audio.num_channels(), 1);
assert_eq!(audio.samples_per_channel(), 4);
Source

pub fn from_vec_with_channels( vec: Vec<T>, channels: usize, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>

Creates multi-channel AudioSamples from a Vec with specified channel count (owned).

The samples in the Vec are assumed to be in row-major order (all samples for channel 0, then all samples for channel 1, etc.).

§Panics
  • If vec is empty
  • If vec.len() is not divisible by channels
§Examples
use audio_samples::{AudioSamples, sample_rate};

// 2 channels, 3 samples each: [ch0_s0, ch0_s1, ch0_s2, ch1_s0, ch1_s1, ch1_s2]
let samples = vec![0.1f32, 0.2, 0.3, 0.4, 0.5, 0.6];
let audio = AudioSamples::from_vec_with_channels(samples, 2, sample_rate!(44100));
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 3);
Source

pub fn from_interleaved_vec( samples: Vec<T>, channels: usize, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>

Creates AudioSamples from interleaved sample data (owned).

Interleaved format: [L0, R0, L1, R1, L2, R2, …] for stereo. This method de-interleaves the data into the internal non-interleaved format.

§Panics
  • If samples is empty
  • If samples.len() is not divisible by channels
§Examples
use audio_samples::{AudioSamples, sample_rate};

// Interleaved stereo: [L0, R0, L1, R1]
let interleaved = vec![0.1f32, 0.4, 0.2, 0.5];
let audio = AudioSamples::from_interleaved_vec(interleaved, 2, sample_rate!(44100));
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 2);
// After de-interleaving: channel 0 = [0.1, 0.2], channel 1 = [0.4, 0.5]
Source

pub fn from_interleaved_slice( samples: &[T], channels: usize, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>

Creates AudioSamples from interleaved slice data (borrowed).

Note: This creates a borrowed view but requires de-interleaving, so it actually creates owned data internally. For zero-copy borrowed access to interleaved data, use new_multi_channel_from_slice with pre-deinterleaved data.

§Panics
  • If samples is empty
  • If samples.len() is not divisible by channels
Source

pub fn from_channels( channels: Vec<Vec<T>>, sample_rate: NonZeroU32, ) -> AudioSampleResult<AudioSamples<'static, T>>

Creates multi-channel AudioSamples from separate channel arrays.

Each element in the vector represents one channel of audio data. All channels must have the same length.

§Errors

Returns an error if:

  • channels is empty
  • any channel is empty (has no samples)
  • channels have different lengths
§Examples
use audio_samples::{AudioSamples, sample_rate};

let left = vec![0.1f32, 0.2, 0.3];
let right = vec![0.4, 0.5, 0.6];
let audio = AudioSamples::from_channels(vec![left, right], sample_rate!(44100)).unwrap();
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 3);
Source

pub fn from_mono_channels( channels: Vec<AudioSamples<'_, T>>, ) -> AudioSampleResult<AudioSamples<'static, T>>

Creates multi-channel AudioSamples from separate mono AudioSamples.

All input AudioSamples must be mono and have the same sample rate and length.

§Errors

Returns an error if:

  • Any input is not mono
  • Sample rates don’t match
  • Lengths don’t match
  • Input is empty
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

let left = AudioSamples::new_mono(array![0.1f32, 0.2, 0.3], 44100);
let right = AudioSamples::new_mono(array![0.4, 0.5, 0.6], 44100);
let stereo = AudioSamples::from_mono_channels(vec![left, right]).unwrap();
assert_eq!(stereo.num_channels(), 2);
Source

pub fn from_iter<I>( iter: I, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>
where I: IntoIterator<Item = T>,

Creates AudioSamples from an iterator of samples (mono, owned).

§Examples
use audio_samples::{AudioSamples, sample_rate};

let audio = AudioSamples::from_iter((0..100).map(|i| i as f32 / 100.0), sample_rate!(44100));
assert_eq!(audio.num_channels(), 1);
assert_eq!(audio.samples_per_channel(), 100);
Source

pub fn from_iter_with_channels<I>( iter: I, channels: usize, sample_rate: NonZeroU32, ) -> AudioSamples<'static, T>
where I: IntoIterator<Item = T>,

Creates AudioSamples from an iterator with specified channel count (owned).

Samples are collected and arranged in row-major order (all samples for channel 0, then channel 1, etc.).

§Panics
  • If the collected sample count is not divisible by channels
§Examples
use audio_samples::{AudioSamples, sample_rate};

// 2 channels, 50 samples each = 100 total samples
let audio = AudioSamples::from_iter_with_channels(
    (0..100).map(|i| i as f32 / 100.0),
    2,
    sample_rate!(44100)
);
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 50);

Trait Implementations§

Source§

impl<T: AudioSample> Add<T> for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: T) -> Self::Output

Performs the + operation. Read more
Source§

impl<T: AudioSample> Add for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Self) -> Self::Output

Performs the + operation. Read more
Source§

impl<T: AudioSample> AddAssign<T> for AudioSamples<'_, T>

Source§

fn add_assign(&mut self, rhs: T)

Performs the += operation. Read more
Source§

impl<T: AudioSample> AddAssign for AudioSamples<'_, T>

Source§

fn add_assign(&mut self, rhs: Self)

Performs the += operation. Read more
Source§

impl<'a, T: AudioSample> AsMut<AudioSamples<'a, T>> for StereoAudioSamples<'a, T>

Source§

fn as_mut(&mut self) -> &mut AudioSamples<'a, T>

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<'a, T: AudioSample> AsRef<AudioSamples<'a, T>> for StereoAudioSamples<'a, T>

Source§

fn as_ref(&self) -> &AudioSamples<'a, T>

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<'a, T: AudioSample> AudioChannelOps<T> for AudioSamples<'a, T>

Source§

fn to_mono<F>( &self, method: MonoConversionMethod<F>, ) -> AudioSampleResult<AudioSamples<'static, T>>
where T: CastFrom<F> + ConvertTo<F>, F: RealFloat + ConvertTo<T>,

Converts multi-channel audio to mono using specified method. Read more
Source§

fn to_stereo<F>( &self, method: StereoConversionMethod<F>, ) -> AudioSampleResult<AudioSamples<'static, T>>
where T: CastFrom<F> + ConvertTo<F>, F: RealFloat + CastInto<T> + ConvertTo<T>,

Converts mono audio to stereo using specified method. Read more
Source§

fn duplicate_to_channels( &self, n_channels: usize, ) -> AudioSampleResult<AudioSamples<'static, T>>

Duplicates mono audio to N channels. Read more
Source§

fn extract_channel( &self, channel_index: usize, ) -> AudioSampleResult<AudioSamples<'static, T>>

Extracts a specific channel from multi-channel audio. Read more
Source§

fn borrow_channel( &self, channel_index: usize, ) -> AudioSampleResult<AudioSamples<'_, T>>

Borrows a specific channel from multi-channel audio. Read more
Source§

fn swap_channels( &mut self, channel1: usize, channel2: usize, ) -> AudioSampleResult<()>

Swaps two channels in multi-channel audio. Read more
Source§

fn pan<F>(&mut self, pan_value: F) -> AudioSampleResult<()>
where T: CastFrom<F> + ConvertTo<F>, F: RealFloat + CastInto<T> + ConvertTo<T>,

Applies pan control to stereo audio. Read more
Source§

fn balance<F>(&mut self, balance: F) -> AudioSampleResult<()>
where T: CastFrom<F> + ConvertTo<F>, F: RealFloat + CastInto<T> + ConvertTo<T>,

Adjusts balance between left and right channels. Read more
Source§

fn apply_to_channel<F>( &mut self, channel_index: usize, func: F, ) -> AudioSampleResult<()>
where F: FnMut(T) -> T, Self: Sized,

Apply a function to a specific channel.
Source§

fn interleave_channels( channels: &[AudioSamples<'_, T>], ) -> AudioSampleResult<AudioSamples<'static, T>>

Interleave multiple channels into one audio sample.
Source§

fn deinterleave_channels( &self, ) -> AudioSampleResult<Vec<AudioSamples<'static, T>>>

Deinterleave audio into separate channel samples.
Source§

impl<'a, T: AudioSample> AudioDynamicRange<T> for AudioSamples<'a, T>

Source§

fn apply_compressor<F>( &mut self, config: &CompressorConfig<F>, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply compression to the audio signal. Read more
Source§

fn apply_limiter<F>( &mut self, config: &LimiterConfig<F>, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply limiting to the audio signal. Read more
Source§

fn apply_compressor_sidechain<F>( &mut self, config: &CompressorConfig<F>, sidechain_signal: &Self, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply compression with external side-chain input. Read more
Source§

fn apply_limiter_sidechain<F>( &mut self, config: &LimiterConfig<F>, sidechain_signal: &Self, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply limiting with external side-chain input. Read more
Source§

fn get_compression_curve<F: RealFloat>( &self, config: &CompressorConfig<F>, input_levels_db: &[F], _sample_rate: F, ) -> AudioSampleResult<Vec<F>>

Analyze the compression curve characteristics. Read more
Source§

fn get_gain_reduction<F>( &self, config: &CompressorConfig<F>, sample_rate: F, ) -> AudioSampleResult<Vec<F>>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Track gain reduction over time. Read more
Source§

fn apply_gate<F>( &mut self, threshold_db: F, ratio: F, attack_ms: F, release_ms: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply gate processing to the audio signal. Read more
Source§

fn apply_expander<F>( &mut self, threshold_db: F, ratio: F, attack_ms: F, release_ms: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply expansion to the audio signal. Read more
Source§

impl<'a, T: AudioSample> AudioEditing<'a, T> for AudioSamples<'a, T>
where i16: ConvertTo<T>, I24: ConvertTo<T>, i32: ConvertTo<T>, f32: ConvertTo<T>, f64: ConvertTo<T>, for<'b> AudioSamples<'b, T>: AudioTypeConversion<'b, T>,

Source§

fn reverse<'b>(&self) -> AudioSamples<'b, T>
where Self: Sized,

Reverses the order of audio samples.

Source§

fn reverse_in_place(&mut self) -> AudioSampleResult<()>
where Self: Sized,

Reverses the order of audio samples in place. This method modifies the original audio samples.

Source§

fn trim<'b, F: RealFloat>( &self, start_seconds: F, end_seconds: F, ) -> AudioSampleResult<AudioSamples<'b, T>>

Extracts a segment of audio between start and end times.

Source§

fn pad<'b, F: RealFloat>( &self, pad_start_seconds: F, pad_end_seconds: F, pad_value: T, ) -> AudioSampleResult<AudioSamples<'b, T>>

Adds padding/silence to the beginning and/or end of the audio.

Source§

fn split<F: RealFloat>( &self, segment_duration_seconds: F, ) -> AudioSampleResult<Vec<AudioSamples<'static, T>>>

Splits audio into segments of specified duration.

Source§

fn concatenate<'b>( segments: &'b [AudioSamples<'b, T>], ) -> AudioSampleResult<AudioSamples<'b, T>>
where Self: Sized, 'b: 'a,

Concatenates multiple audio segments into one.

Source§

fn mix<F>( sources: &[Self], weights: Option<&[F]>, ) -> AudioSampleResult<AudioSamples<'static, T>>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>, Self: Sized,

Mixes multiple audio sources together.

Source§

fn fade_in<F>( &mut self, duration_seconds: F, curve: FadeCurve<F>, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Applies fade-in envelope over specified duration.

Source§

fn fade_out<F>( &mut self, duration_seconds: F, curve: FadeCurve<F>, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Applies fade-out envelope over specified duration.

Source§

fn repeat(&self, count: usize) -> AudioSampleResult<AudioSamples<'static, T>>

Repeats the audio signal a specified number of times.

Source§

fn trim_silence<F>( &self, threshold_db: F, ) -> AudioSampleResult<AudioSamples<'static, T>>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Crops audio to remove silence from the beginning and end using a dB threshold.

Source§

fn perturb<'b, F>( &self, config: &PerturbationConfig<F>, ) -> AudioSampleResult<AudioSamples<'b, T>>

Applies perturbation to audio samples for data augmentation.

Source§

fn perturb_<F>( &mut self, config: &PerturbationConfig<F>, ) -> AudioSampleResult<()>

Applies perturbation to audio samples in place.

Source§

fn pad_samples_right<'b>( &self, target_num_samples: usize, pad_value: T, ) -> AudioSampleResult<AudioSamples<'b, T>>

Pad samples to the right to reach a target number of samples.
Source§

fn pad_to_duration<'b, F: RealFloat>( &self, target_duration_seconds: F, pad_value: T, pad_side: PadSide, ) -> AudioSampleResult<AudioSamples<'b, T>>

Pad audio to a target duration.
Source§

fn stack(sources: &[Self]) -> AudioSampleResult<AudioSamples<'static, T>>

Stacks multiple mono audio samples into a multi-channel audio sample.
Source§

fn trim_all_silence<F>( &self, threshold_db: F, min_silence_duration_seconds: F, ) -> AudioSampleResult<AudioSamples<'static, T>>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Trim silence anywhere in the audio.
Source§

fn concatenate_owned<'b>( segments: Vec<AudioSamples<'_, T>>, ) -> AudioSampleResult<AudioSamples<'b, T>>
where Self: Sized,

Concatenates multiple owned audio segments into one.
Source§

impl<'a, T: AudioSample> AudioIirFiltering<T> for AudioSamples<'a, T>

Source§

fn apply_iir_filter<F>( &mut self, design: &IirFilterDesign<F>, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply an IIR filter using the specified design parameters. Read more
Source§

fn butterworth_lowpass<F>( &mut self, order: usize, cutoff_frequency: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a simple Butterworth low-pass filter. Read more
Source§

fn butterworth_highpass<F>( &mut self, order: usize, cutoff_frequency: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a simple Butterworth high-pass filter. Read more
Source§

fn butterworth_bandpass<F>( &mut self, order: usize, low_frequency: F, high_frequency: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a simple Butterworth band-pass filter. Read more
Source§

fn chebyshev_i<F>( &mut self, order: usize, cutoff_frequency: F, passband_ripple: F, sample_rate: F, response: FilterResponse, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a Chebyshev Type I filter. Read more
Source§

fn frequency_response<F>( &self, frequencies: &[F], _sample_rate: F, ) -> AudioSampleResult<(Vec<F>, Vec<F>)>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Get the frequency response of the current filter. Read more
Source§

impl<'a, T: AudioSample> AudioParametricEq<'a, T> for AudioSamples<'a, T>
where i16: ConvertTo<T>, I24: ConvertTo<T>, i32: ConvertTo<T>, f32: ConvertTo<T>, f64: ConvertTo<T>, for<'b> AudioSamples<'b, T>: AudioTypeConversion<'b, T>,

Source§

fn apply_parametric_eq<F>( &mut self, eq: &ParametricEq<F>, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a parametric EQ to the audio signal. Read more
Source§

fn apply_eq_band<F>( &mut self, band: &EqBand<F>, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a single EQ band to the audio signal. Read more
Source§

fn apply_peak_filter<F>( &mut self, frequency: F, gain_db: F, q_factor: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a peak/notch filter at the specified frequency. Read more
Source§

fn apply_low_shelf<F>( &mut self, frequency: F, gain_db: F, q_factor: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a low shelf filter. Read more
Source§

fn apply_high_shelf<F>( &mut self, frequency: F, gain_db: F, q_factor: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Apply a high shelf filter. Read more
Source§

fn apply_three_band_eq<F>( &mut self, low_freq: F, low_gain: F, mid_freq: F, mid_gain: F, mid_q: F, high_freq: F, high_gain: F, sample_rate: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Create and apply a common 3-band EQ (low shelf, mid peak, high shelf). Read more
Source§

fn eq_frequency_response<F>( &self, eq: &ParametricEq<F>, frequencies: &[F], sample_rate: F, ) -> AudioSampleResult<(Vec<F>, Vec<F>)>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Get the combined frequency response of a parametric EQ. Read more
Source§

impl<'a, T: AudioSample> AudioProcessing<T> for AudioSamples<'a, T>
where i16: ConvertTo<T>, I24: ConvertTo<T>, i32: ConvertTo<T>, f32: ConvertTo<T>, f64: ConvertTo<T>, for<'b> AudioSamples<'b, T>: AudioTypeConversion<'b, T>,

Source§

fn normalize( &mut self, min: T, max: T, method: NormalizationMethod, ) -> AudioSampleResult<()>

Normalizes audio samples using the specified method and range.

This method modifies the audio samples in-place to fit within the target range using different normalization strategies. Normalization is useful for ensuring consistent signal levels and preparing audio for further processing.

§Arguments
  • min - Minimum value of the target range
  • max - Maximum value of the target range
  • method - The normalization method to use (MinMax, Peak, Mean, Median, or ZScore)
§Returns

Ok(()) on success.

§Errors

Returns an error if:

  • The min value is greater than or equal to the max value
  • Type conversion fails during normalization
  • Computing statistical values fails (for certain methods)
§Examples
use audio_samples::{AudioSamples, AudioProcessing, NormalizationMethod};
use ndarray::array;

let data = array![1.0f32, -3.0, 2.0, -1.0];
let mut audio = AudioSamples::new_mono(data, 44100);
audio.normalize(-1.0, 1.0, NormalizationMethod::Peak).unwrap();
assert!(audio.peak() <= 1.0);
Source§

fn scale(&mut self, factor: T)

Scales all audio samples by a constant factor.

This is equivalent to adjusting the volume/amplitude of the signal. A factor of 1.0 leaves the signal unchanged, values > 1.0 amplify, and values < 1.0 attenuate the signal.

§Arguments
  • factor - The scaling factor to apply to all samples
§Examples
use audio_samples::{AudioSamples, AudioProcessing};
use ndarray::array;

let data = array![1.0f32, -1.0, 0.5];
let mut audio = AudioSamples::new_mono(data, 44100);
audio.scale(2.0);
// Signal is now [2.0, -2.0, 1.0]
Source§

fn remove_dc_offset(&mut self) -> AudioSampleResult<()>

Removes DC offset by subtracting the mean value.

This centers the audio around zero and removes any constant bias that may have been introduced during recording or processing. DC offset can cause issues in audio processing and should generally be removed.

§Returns

Ok(()) on success.

§Examples
use audio_samples::{AudioSamples, AudioProcessing, AudioStatistics};
use ndarray::array;

let data = array![2.0f32, 3.0, 4.0, 5.0]; // Has DC offset
let mut audio = AudioSamples::new_mono(data, 44100);
audio.remove_dc_offset().unwrap();
let mean = audio.mean::<f32>().unwrap();
assert!((mean).abs() < 1e-6); // Mean is now ~0
Source§

fn clip(&mut self, min_val: T, max_val: T) -> AudioSampleResult<()>

Clips audio samples to the specified range.

Any samples outside the range will be limited to the range boundaries. This is useful for preventing clipping distortion and ensuring samples stay within valid ranges for further processing or output.

§Arguments
  • min_val - Minimum allowed value
  • max_val - Maximum allowed value
§Returns

Ok(()) on success.

§Errors

Returns an error if min_val > max_val.

§Examples
use audio_samples::{AudioSamples, AudioProcessing};
use ndarray::array;

let data = array![2.0f32, -3.0, 1.5, -0.5];
let mut audio = AudioSamples::new_mono(data, 44100);
audio.clip(-1.0, 1.0).unwrap();
// Values are now [1.0, -1.0, 1.0, -0.5]
Source§

fn apply_window(&mut self, window: &[T]) -> AudioSampleResult<()>

Applies a windowing function to the audio samples.

Multiplies each audio sample by the corresponding window coefficient. Windowing is commonly used before FFT operations to reduce spectral leakage. The window length must match the number of samples in the audio.

§Arguments
  • window - Array of window coefficients to apply
§Returns

Ok(()) on success.

§Errors

Returns an error if the window length doesn’t match the audio length.

§Examples
use audio_samples::{AudioSamples, AudioProcessing};
use ndarray::array;

let data = array![1.0f32, 1.0, 1.0, 1.0];
let mut audio = AudioSamples::new_mono(data, 44100);
let window = [1.0, 0.5, 0.5, 1.0]; // Simple window
audio.apply_window(&window).unwrap();
// Audio is now [1.0, 0.5, 0.5, 1.0]
Source§

fn apply_filter(&mut self, filter_coeffs: &[T]) -> AudioSampleResult<()>

Applies a digital filter to the audio samples using convolution.

This implements basic FIR filtering using direct convolution.

Source§

fn mu_compress(&mut self, mu: T) -> AudioSampleResult<()>

Applies μ-law compression to the audio samples.

Source§

fn mu_expand(&mut self, mu: T) -> AudioSampleResult<()>

Applies μ-law expansion (decompression) to the audio samples.

First the mu value is converted to f64, then the expansion is applied. First the mu value is converted to f64, then the expansion is applied. Second, the result is converted back to T.

Source§

fn low_pass_filter<F>(&mut self, cutoff_hz: F) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: CastFrom<F> + ConvertTo<F>,

Applies a low-pass filter with the specified cutoff frequency.

Source§

fn high_pass_filter<F>(&mut self, cutoff_hz: F) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: CastFrom<F> + ConvertTo<F>,

Applies a high-pass filter with the specified cutoff frequency.

Source§

fn band_pass_filter<F>( &mut self, low_cutoff_hz: F, high_cutoff_hz: F, ) -> AudioSampleResult<()>
where F: RealFloat + ConvertTo<T>, T: CastFrom<F> + ConvertTo<F>,

Applies a band-pass filter between low and high frequencies.

Source§

impl<'a, T: AudioSample> AudioStatistics<'a, T> for AudioSamples<'a, T>
where i16: ConvertTo<T>, I24: ConvertTo<T>, i32: ConvertTo<T>, f32: ConvertTo<T>, f64: ConvertTo<T>, for<'b> AudioSamples<'b, T>: AudioTypeConversion<'b, T>,

Source§

fn peak(&self) -> T

Returns the peak (maximum absolute value) in the audio samples.

§Returns

The maximum absolute value found across all samples and channels. Returns the default value for type T if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -3.0, 2.5, -1.5];
let audio = AudioSamples::new_mono(data, 44100);
assert_eq!(audio.peak(), 3.0);
Source§

fn min_sample(&self) -> T

Returns the minimum value in the audio samples.

§Returns

The smallest sample value found across all samples and channels. Returns the default value for type T if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -3.0, 2.5, -1.5];
let audio = AudioSamples::new_mono(data, 44100);
assert_eq!(audio.min_sample(), -3.0);
Source§

fn max_sample(&self) -> T

Returns the maximum value in the audio samples.

§Returns

The largest sample value found across all samples and channels. Returns the default value for type T if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -3.0, 2.5, -1.5];
let audio = AudioSamples::new_mono(data, 44100);
assert_eq!(audio.max_sample(), 2.5);
Source§

fn mean<F: RealFloat>(&self) -> F

Computes the mean (average) of the audio samples.

§Returns

Some(mean) containing the arithmetic mean of all samples across all channels, or None if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -1.0, 2.0, -2.0];
let audio = AudioSamples::new_mono(data, 44100);
assert_eq!(audio.mean::<f32>(), 0.0);
Source§

fn rms<F: RealFloat>(&self) -> F

Computes the Root Mean Square (RMS) of the audio samples.

RMS = sqrt(mean(x^2)) where x is the audio signal. This provides a measure of the signal’s energy content and is commonly used for loudness estimation.

§Returns

Some(rms) containing the RMS value of all samples across all channels, or None if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -1.0, 1.0, -1.0];
let audio = AudioSamples::new_mono(data, 44100);
let rms = audio.rms::<f32>();
assert!((rms - 1.0).abs() < 1e-6);
Source§

fn variance<F: RealFloat>(&self) -> F

Computes the statistical variance of the audio samples.

Variance = mean((x - mean(x))^2). This measures the spread of the data points around the mean value.

§Returns

Some(variance) containing the variance of all samples across all channels, or None if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, 2.0, 3.0, 4.0];
let audio = AudioSamples::new_mono(data, 44100);
let variance = audio.variance::<f32>();
assert!((variance - 1.25).abs() < 1e-6);
Source§

fn std_dev<F: RealFloat>(&self) -> F

Computes the standard deviation of the audio samples.

Standard deviation is the square root of variance. It provides a measure of how spread out the sample values are from the mean, in the same units as the original data.

§Returns

Some(std_dev) containing the standard deviation of all samples across all channels, or None if the audio data is empty.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, 2.0, 3.0, 4.0];
let audio = AudioSamples::new_mono(data, 44100);
let std_dev = audio.std_dev::<f32>();
assert!((std_dev - (1.25_f32).sqrt()).abs() < 1e-6);
Source§

fn zero_crossings(&self) -> usize

Counts the number of zero crossings in the audio signal.

Zero crossings occur when the signal changes sign between adjacent samples. This metric is useful for pitch detection, signal analysis, and estimating the noisiness of a signal.

§Returns

The total number of zero crossings across all channels. Returns 0 if the audio has fewer than 2 samples.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -1.0, 1.0, -1.0];
let audio = AudioSamples::new_mono(data, 44100);
assert_eq!(audio.zero_crossings(), 3);
Source§

fn zero_crossing_rate<F: RealFloat>(&self) -> F

Computes the zero crossing rate (crossings per second).

This normalizes the zero crossing count by the signal duration, providing a frequency-like measure that is independent of signal length.

§Returns

The number of zero crossings per second, or 0.0 if the signal duration is zero.

§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data = array![1.0f32, -1.0, 1.0, -1.0];
let audio = AudioSamples::new_mono(data, 44100);
let zcr = audio.zero_crossing_rate::<f32>();
assert!(zcr > 0.0);
Source§

fn cross_correlation<F: RealFloat>( &self, other: &Self, max_lag: usize, ) -> AudioSampleResult<Vec<F>>

Computes cross-correlation with another audio signal.

Cross-correlation measures the similarity between two signals as a function of the displacement of one relative to the other. Useful for signal alignment, pattern matching, and delay estimation.

§Arguments
  • other - The second audio signal to correlate with
  • max_lag - Maximum lag offset to compute correlations for
§Returns

Ok(correlations) containing correlation values for each lag offset from 0 to max_lag.

§Errors

Returns an error if:

  • Signals have different numbers of channels
  • Either signal is empty
  • max_lag is zero
§Examples
use audio_samples::{AudioSamples, AudioStatistics};
use ndarray::array;

let data1 = array![1.0f32, 0.0, -1.0, 0.0];
let data2 = array![0.0, 1.0, 0.0, -1.0];
let audio1 = AudioSamples::new_mono(data1, 44100);
let audio2 = AudioSamples::new_mono(data2, 44100);
let xcorr = audio1.cross_correlation::<f32>(&audio2, 3).unwrap();
assert_eq!(xcorr.len(), 4); // 0 to max_lag inclusive
Source§

fn amplitude(&self) -> T

Alias for peak to match common terminology
Source§

impl<'a, T> AudioTypeConversion<'a, T> for AudioSamples<'a, T>

Source§

fn to_format<O>(&self) -> AudioSamples<'static, O>
where T: ConvertTo<O>, O: AudioSample + ConvertTo<T>,

Converts to different sample type, borrowing the original. Read more
Source§

fn to_type<O: AudioSample + ConvertTo<T>>(self) -> AudioSamples<'static, O>
where T: ConvertTo<O>,

Converts to different sample type, consuming the original.
Source§

fn cast_as<O>(&self) -> AudioSamples<'static, O>
where O: AudioSample + CastFrom<T>,

Casts to different sample type without audio-aware scaling, borrowing the original. Read more
Source§

fn cast_to<O>(self) -> AudioSamples<'static, O>
where O: AudioSample + CastFrom<T>,

Casts to different sample type without audio-aware scaling, consuming the original. Read more
Source§

fn as_float<F>(&self) -> AudioSamples<'static, F>
where F: RealFloat + ConvertTo<T>, T: ConvertTo<F>,

Converts audio samples to a floating-point type.
Source§

fn as_f64(&self) -> AudioSamples<'static, f64>
where T: ConvertTo<f64>,

Converts to double precision floating-point format.
Source§

fn as_f32(&self) -> AudioSamples<'static, f32>
where T: ConvertTo<f32>,

Converts to single precision floating-point format.
Source§

fn as_i32(&self) -> AudioSamples<'static, i32>
where T: ConvertTo<i32>,

Converts to 32-bit integer format.
Source§

fn as_i16(&self) -> AudioSamples<'static, i16>
where T: ConvertTo<i16>,

Converts to 16-bit integer format (most common). Standard format for CD audio and many audio files.
Source§

fn as_i24(&self) -> AudioSamples<'static, I24>
where T: ConvertTo<I24>,

Converts to 24-bit integer format. Common in professional audio workflows.
Source§

fn cast_as_i16(&self) -> AudioSamples<'static, i16>
where i16: CastFrom<T>,

Casts audio samples to i16 format.
Source§

fn cast_to_i16(self) -> AudioSamples<'static, i16>
where i16: CastFrom<T>, Self: Sized,

Converts audio samples to i16 format.
Source§

fn cast_as_i24(&self) -> AudioSamples<'static, I24>
where I24: CastFrom<T>,

Casts audio samples to I24 format.
Source§

fn cast_to_i24(self) -> AudioSamples<'static, I24>
where I24: CastFrom<T>, Self: Sized,

Converts audio samples to I24 format.
Source§

fn cast_as_i32(&self) -> AudioSamples<'static, i32>
where i32: CastFrom<T>,

Casts audio samples to i32 format.
Source§

fn cast_to_i32(self) -> AudioSamples<'static, i32>
where i32: CastFrom<T>, Self: Sized,

Converts audio samples to i32 format.
Source§

fn cast_as_f32(&self) -> AudioSamples<'static, f32>
where f32: CastFrom<T>,

Casts audio samples to f32 format.
Source§

fn cast_to_f32(self) -> AudioSamples<'static, f32>
where f32: CastFrom<T>, Self: Sized,

Converts audio samples to f32 format.
Source§

fn cast_as_f64(&self) -> AudioSamples<'static, f64>
where f64: CastFrom<T>, Self: Sized,

Casts audio samples to f64 format.
Source§

impl<'a, T: AudioSample> AudioVoiceActivityDetection<'a, T> for AudioSamples<'a, T>

Source§

fn voice_activity_mask<F: RealFloat>( &self, config: &VadConfig<F>, ) -> AudioSampleResult<Vec<bool>>

Compute a per-frame speech activity mask. Read more
Source§

fn speech_regions<F: RealFloat>( &self, config: &VadConfig<F>, ) -> AudioSampleResult<Vec<(usize, usize)>>

Compute contiguous speech regions as (start_sample, end_sample) pairs. Read more
Source§

impl<'a, T: AudioSample> Clone for AudioSamples<'a, T>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a, T: Debug + AudioSample> Debug for AudioSamples<'a, T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'a, T: AudioSample> Display for AudioSamples<'a, T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: AudioSample> Div<T> for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: T) -> Self::Output

Performs the / operation. Read more
Source§

impl<T: AudioSample> Div for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the / operator.
Source§

fn div(self, rhs: Self) -> Self::Output

Performs the / operation. Read more
Source§

impl<T: AudioSample> DivAssign<T> for AudioSamples<'_, T>

Source§

fn div_assign(&mut self, rhs: T)

Performs the /= operation. Read more
Source§

impl<T: AudioSample> DivAssign for AudioSamples<'_, T>

Source§

fn div_assign(&mut self, rhs: Self)

Performs the /= operation. Read more
Source§

impl<T: AudioSample> From<StereoAudioSamples<'static, T>> for AudioSamples<'static, T>

Source§

fn from(stereo: StereoAudioSamples<'static, T>) -> Self

Converts to this type from the input type.
Source§

impl<'a, T: AudioSample> Index<[usize; 2]> for AudioSamples<'a, T>

Source§

fn index(&self, index: [usize; 2]) -> &Self::Output

Index into audio samples by [channel, sample] coordinates.

This works for both mono and multi-channel audio:

  • For mono: only [0, sample_index] is valid
  • For multi-channel: [channel_index, sample_index]
§Panics
  • If channel or sample index is out of bounds
Source§

type Output = T

The returned type after indexing.
Source§

impl<'a, T: AudioSample> Index<(usize, usize)> for AudioSamples<'a, T>

Source§

fn index(&self, index: (usize, usize)) -> &Self::Output

Index into audio samples by (channel, sample) coordinates.

This works for both mono and multi-channel audio:

  • For mono: only (0, sample_index) is valid
  • For multi-channel: (channel_index, sample_index)
§Panics
  • If channel or sample index is out of bounds
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Mono audio
let mono_data = array![1.0f32, 2.0, 3.0];
let mono_audio = AudioSamples::new_mono(mono_data, 44100);
assert_eq!(mono_audio[(0, 1)], 2.0);

// Multi-channel audio
let stereo_data = array![[1.0f32, 2.0], [3.0, 4.0]];
let stereo_audio = AudioSamples::new_multi_channel(stereo_data, 44100);
assert_eq!(stereo_audio[(0, 1)], 2.0); // Channel 0, sample 1
assert_eq!(stereo_audio[(1, 0)], 3.0); // Channel 1, sample 0
Source§

type Output = T

The returned type after indexing.
Source§

impl<'a, T: AudioSample> Index<usize> for AudioSamples<'a, T>

Source§

fn index(&self, index: usize) -> &Self::Output

Index into mono audio samples by sample index.

For mono audio, this returns the sample at the given index. For multi-channel audio, this will panic - use [(channel, sample)] instead.

§Panics
  • If index is out of bounds
  • If used on multi-channel audio (use 2D indexing instead)
§Examples
use audio_samples::AudioSamples;
use ndarray::array;

let data = array![1.0f32, 2.0, 3.0, 4.0, 5.0];
let audio = AudioSamples::new_mono(data, 44100);

assert_eq!(audio[0], 1.0);
assert_eq!(audio[2], 3.0);
Source§

type Output = T

The returned type after indexing.
Source§

impl<'a, T: AudioSample> IndexMut<(usize, usize)> for AudioSamples<'a, T>

Source§

fn index_mut(&mut self, index: (usize, usize)) -> &mut Self::Output

Mutable index into audio samples by (channel, sample) coordinates.

This works for both mono and multi-channel audio:

  • For mono: only (0, sample_index) is valid
  • For multi-channel: (channel_index, sample_index)
§Panics
  • If channel or sample index is out of bounds
Source§

impl<'a, T: AudioSample> IndexMut<usize> for AudioSamples<'a, T>

Source§

fn index_mut(&mut self, index: usize) -> &mut Self::Output

Mutable index into mono audio samples by sample index.

For mono audio, this returns a mutable reference to the sample at the given index. For multi-channel audio, this will panic - use [(channel, sample)] instead.

§Panics
  • If index is out of bounds
  • If used on multi-channel audio (use 2D indexing instead)
Source§

impl<'a, T: AudioSample> IntoIterator for AudioSamples<'a, T>

Source§

fn into_iter(self) -> Self::IntoIter

Consumes the AudioSamples and returns an iterator over the samples in interleaved order.

For mono audio, this is simply the samples in order. For multi-channel audio, this interleaves samples from each channel.

§Examples
use audio_samples::AudioSamples;
use ndarray::array;

// Mono audio
let mono_data = array![1.0f32, 2.0, 3.0];
let mono_audio = AudioSamples::new_mono(mono_data, 44100);
let mono_samples: Vec<f32> = mono_audio.into_iter().collect();
assert_eq!(mono_samples, vec![1.0, 2.0, 3.0]);

// Multi-channel audio
let stereo_data = array![[1.0f32, 2.0], [3.0, 4.0]];
let stereo_audio = AudioSamples::new_multi_channel(stereo_data, 44100);
let stereo_samples: Vec<f32> = stereo_audio.into_iter().collect();
assert_eq!(stereo_samples, vec![1.0, 3.0, 2.0, 4.0]); // Interleaved
Source§

type Item = T

The type of the elements being iterated over.
Source§

type IntoIter = IntoIter<T>

Which kind of iterator are we turning this into?
Source§

impl<T: AudioSample> Mul<T> for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: T) -> Self::Output

Performs the * operation. Read more
Source§

impl<T: AudioSample> Mul for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Self) -> Self::Output

Performs the * operation. Read more
Source§

impl<T: AudioSample> MulAssign<T> for AudioSamples<'_, T>

Source§

fn mul_assign(&mut self, rhs: T)

Performs the *= operation. Read more
Source§

impl<T: AudioSample> MulAssign for AudioSamples<'_, T>

Source§

fn mul_assign(&mut self, rhs: Self)

Performs the *= operation. Read more
Source§

impl<T> Neg for AudioSamples<'_, T>
where T: Neg<Output = T> + AudioSample,

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the - operator.
Source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
Source§

impl<'a, T: PartialEq + AudioSample> PartialEq for AudioSamples<'a, T>

Source§

fn eq(&self, other: &AudioSamples<'a, T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: AudioSample> Sub<T> for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: T) -> Self::Output

Performs the - operation. Read more
Source§

impl<T: AudioSample> Sub for AudioSamples<'_, T>

Source§

type Output = AudioSamples<'_, T>

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Self) -> Self::Output

Performs the - operation. Read more
Source§

impl<T: AudioSample> SubAssign<T> for AudioSamples<'_, T>

Source§

fn sub_assign(&mut self, rhs: T)

Performs the -= operation. Read more
Source§

impl<T: AudioSample> SubAssign for AudioSamples<'_, T>

Source§

fn sub_assign(&mut self, rhs: Self)

Performs the -= operation. Read more
Source§

impl<T: AudioSample> TryFrom<(&[T], u32)> for AudioSamples<'static, T>

Create mono AudioSamples from (&[T], sample_rate) tuple (creates owned copy).

§Examples

use audio_samples::AudioSamples;
use std::convert::TryFrom;

let data = [0.1f32, 0.2, 0.3];
let audio = AudioSamples::try_from((data.as_slice(), 44100_u32)).unwrap();
assert_eq!(audio.num_channels(), 1);
assert_eq!(audio.samples_per_channel(), 3);
Source§

type Error = AudioSampleError

The type returned in the event of a conversion error.
Source§

fn try_from((samples, sample_rate): (&[T], u32)) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<T: AudioSample> TryFrom<(Vec<T>, u32)> for AudioSamples<'static, T>

Create mono AudioSamples from (Vec<T>, sample_rate) tuple.

§Examples

use audio_samples::AudioSamples;
use std::convert::TryFrom;

let audio = AudioSamples::try_from((vec![0.1f32, 0.2, 0.3], 44100_u32)).unwrap();
assert_eq!(audio.num_channels(), 1);
assert_eq!(audio.samples_per_channel(), 3);
Source§

type Error = AudioSampleError

The type returned in the event of a conversion error.
Source§

fn try_from((samples, sample_rate): (Vec<T>, u32)) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<T: AudioSample> TryFrom<(Vec<T>, usize, u32)> for AudioSamples<'static, T>

Create multi-channel AudioSamples from (Vec<T>, channels, sample_rate) tuple.

§Examples

use audio_samples::AudioSamples;
use std::convert::TryFrom;

// 2 channels, 2 samples each
let audio = AudioSamples::try_from((vec![0.1f32, 0.2, 0.3, 0.4], 2_usize, 44100_u32)).unwrap();
assert_eq!(audio.num_channels(), 2);
assert_eq!(audio.samples_per_channel(), 2);
Source§

type Error = AudioSampleError

The type returned in the event of a conversion error.
Source§

fn try_from( (samples, channels, sample_rate): (Vec<T>, usize, u32), ) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<'a, T: AudioSample> TryFrom<(u32, u32, Vec<T>)> for AudioSamples<'a, T>

Source§

fn try_from( (n_channels, sample_rate, samples): (u32, u32, Vec<T>), ) -> Result<Self, Self::Error>

Create AudioSamples from a sample rate and a vector of samples (assumed mono).

Source§

type Error = AudioSampleError

The type returned in the event of a conversion error.
Source§

impl<T: AudioSample> TryFrom<AudioSamples<'static, T>> for StereoAudioSamples<'static, T>

Zero-copy conversion from owned AudioSamples to StereoAudioSamples

Source§

type Error = AudioSampleError

The type returned in the event of a conversion error.
Source§

fn try_from(audio: AudioSamples<'static, T>) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl<'a, T: AudioSample> StructuralPartialEq for AudioSamples<'a, T>

Auto Trait Implementations§

§

impl<'a, T> Freeze for AudioSamples<'a, T>

§

impl<'a, T> RefUnwindSafe for AudioSamples<'a, T>
where T: RefUnwindSafe,

§

impl<'a, T> Send for AudioSamples<'a, T>

§

impl<'a, T> Sync for AudioSamples<'a, T>

§

impl<'a, T> Unpin for AudioSamples<'a, T>

§

impl<'a, T> !UnwindSafe for AudioSamples<'a, T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V