#[non_exhaustive]pub struct StereoAudioSamples<'a, T>(pub AudioSamples<'a, T>)
where
T: StandardSample;Expand description
A newtype wrapper around AudioSamples that guarantees exactly two channels (stereo).
§Purpose
StereoAudioSamples encodes the stereo invariant in the type system so that code
expecting a stereo signal can accept it without re-checking the channel count at
every call site.
§Intended Usage
Construct via StereoAudioSamples::new or TryFrom<AudioSamples>. The inner
AudioSamples is accessible through Deref / DerefMut / AsRef / AsMut.
§Invariants
num_channels()always returns2.- The inner data is always the
Multivariant ofAudioData.
§Assumptions
All constructors reject non-stereo input at runtime; there is no way to construct
a StereoAudioSamples with fewer or more than two channels through the public API.
Tuple Fields (Non-exhaustive)§
This struct is marked as non-exhaustive
Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.0: AudioSamples<'a, T>Implementations§
Source§impl<'a, T> StereoAudioSamples<'a, T>where
T: StandardSample,
impl<'a, T> StereoAudioSamples<'a, T>where
T: StandardSample,
Sourcepub fn new(
stereo_data: AudioData<'a, T>,
sample_rate: NonZeroU32,
) -> AudioSampleResult<Self>
pub fn new( stereo_data: AudioData<'a, T>, sample_rate: NonZeroU32, ) -> AudioSampleResult<Self>
Creates a new StereoAudioSamples from audio data with exactly 2 channels.
§Errors
Returns an error if stereo_data is mono or has a channel count other than 2.
Sourcepub fn with_channels<R, F>(&self, f: F) -> AudioSampleResult<R>
pub fn with_channels<R, F>(&self, f: F) -> AudioSampleResult<R>
Safely access individual channels with borrowed references for efficient processing.
This method provides zero-copy access to the left and right channels, allowing efficient operations like STFT on individual channels without data duplication.
§Arguments
f- Closure that receives borrowed left and right channel data
§Returns
The result of the closure operation
§Example
use audio_samples::{AudioSamples, StereoAudioSamples, sample_rate, AudioSampleResult};
use ndarray::array;
let stereo_data = array![[0.1f32, 0.2, 0.3], [0.4, 0.5, 0.6]];
let audio = AudioSamples::new_multi_channel(stereo_data, sample_rate!(44100)).unwrap();
let stereo: StereoAudioSamples<'static, f32> = StereoAudioSamples::try_from(audio).unwrap();
stereo.with_channels(|left, right| -> AudioSampleResult<()> {
// left and right are borrowed AudioSamples<'_, f32>
println!("Left channel samples: {}", left.len());
println!("Right channel samples: {}", right.len());
Ok(())
}).unwrap();§Errors
Methods from Deref<Target = AudioSamples<'a, T>>§
Sourcepub fn frames(&'a self) -> FrameIterator<'a, T> ⓘ
pub fn frames(&'a self) -> FrameIterator<'a, T> ⓘ
Returns an iterator over frames, where each frame is a snapshot of one sample from each channel at the same point in time.
For mono audio, each frame contains exactly one sample. For multi-channel audio, each frame contains one sample per channel in channel-index order.
§Returns
A FrameIterator that yields one AudioSamples view per time index.
The iterator yields exactly self.samples_per_channel() frames.
§Panics
Does not panic.
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
let audio = AudioSamples::new_multi_channel(
array![[1.0f32, 2.0, 3.0], [4.0, 5.0, 6.0]],
sample_rate!(44100),
).unwrap();
// Three time steps → three frames.
assert_eq!(audio.frames().count(), 3);
// Each frame spans all channels.
for frame in audio.frames() {
assert_eq!(frame.num_channels().get(), 2);
}Sourcepub fn channels<'iter>(&'iter self) -> ChannelIterator<'iter, 'a, T> ⓘ
pub fn channels<'iter>(&'iter self) -> ChannelIterator<'iter, 'a, T> ⓘ
Returns an iterator over complete channels.
Each iteration yields the full temporal sequence of samples belonging to one channel. Channels are yielded in increasing channel-index order.
Each yielded value is an owned AudioSamples instance containing exactly
one mono channel. This involves allocation and data copying.
§Returns
A ChannelIterator yielding one owned AudioSamples per channel.
The iterator yields exactly self.num_channels() items.
§Panics
Does not panic.
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
let audio = AudioSamples::new_multi_channel(
array![[1.0f32, 2.0, 3.0], [4.0, 5.0, 6.0]],
sample_rate!(44100),
).unwrap();
let channels: Vec<_> = audio.channels().collect();
assert_eq!(channels.len(), 2);
assert_eq!(channels[0].samples_per_channel().get(), 3);Sourcepub fn apply_to_frames<F>(&mut self, f: F)
pub fn apply_to_frames<F>(&mut self, f: F)
Applies a mutable function to every frame without requiring a borrowing-safe iterator.
The callback receives the frame index and a mutable slice containing the samples for that frame across all channels. For mono audio the slice has length 1. For multi-channel audio the slice is a temporary buffer ordered by channel index; changes are written back into the underlying storage after the callback returns.
Use this method when in-place, frame-wise mutation is needed and the immutable
AudioSamples::frames iterator is insufficient.
§Arguments
– f — a closure of the form FnMut(frame_index: usize, frame_samples: &mut [T]).
– frame_index — zero-based index of the current frame.
– frame_samples — mutable slice of length num_channels() for the current frame.
§Returns
() — the audio is modified in place.
§Panics
Does not panic.
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
let mut audio = AudioSamples::new_multi_channel(
array![[1.0f32, 2.0, 3.0], [4.0, 5.0, 6.0]],
sample_rate!(44100),
).unwrap();
// Double every sample frame-by-frame.
audio.apply_to_frames(|_frame_idx, frame| {
for s in frame { *s *= 2.0; }
});
assert_eq!(
audio.as_multi_channel().unwrap(),
&array![[2.0f32, 4.0, 6.0], [8.0, 10.0, 12.0]],
);Sourcepub fn try_apply_to_channel_data<F>(&mut self, f: F) -> AudioSampleResult<()>
pub fn try_apply_to_channel_data<F>(&mut self, f: F) -> AudioSampleResult<()>
Applies a mutable function to each channel’s contiguous sample slice.
This is the fallible counterpart to AudioSamples::apply_to_channel_data.
It requires that the underlying ndarray storage is contiguous in memory.
Non-contiguous layouts (such as after certain in-place reversals or
non-standard strides) will cause this method to return an error.
The callback receives the channel index and a mutable slice of all samples for that channel.
§Arguments
– f — a closure of the form FnMut(channel_index: usize, channel_samples: &mut [T]).
– channel_index — zero-based index of the channel being processed.
– channel_samples — mutable slice of all samples belonging to that channel.
§Returns
Ok(()) if all channels were processed successfully.
§Errors
Returns crate::AudioSampleError::Layout with variant NonContiguous if the
underlying multi-channel storage is not contiguous in memory.
§Panics
Does not panic.
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
let mut audio = AudioSamples::new_multi_channel(
array![[1.0f32, 2.0, 3.0], [4.0, 5.0, 6.0]],
sample_rate!(44100),
).unwrap();
// Halve channel 0, double channel 1.
audio.try_apply_to_channel_data(|ch, samples| {
let gain = if ch == 0 { 0.5 } else { 2.0 };
for s in samples { *s *= gain; }
}).unwrap();
assert_eq!(
audio.as_multi_channel().unwrap(),
&array![[0.5f32, 1.0, 1.5], [8.0, 10.0, 12.0]],
);Sourcepub fn apply_to_channel_data<F>(&mut self, f: F)
pub fn apply_to_channel_data<F>(&mut self, f: F)
Applies a mutable function to each channel’s contiguous sample slice.
This is the infallible counterpart to AudioSamples::try_apply_to_channel_data.
It panics if the underlying storage is not contiguous; prefer the fallible
variant when working with audio that may have non-standard memory layouts.
The callback receives the channel index and a mutable slice of all samples for that channel.
§Arguments
– f — a closure of the form FnMut(channel_index: usize, channel_samples: &mut [T]).
– channel_index — zero-based index of the channel being processed.
– channel_samples — mutable slice of all samples belonging to that channel.
§Returns
() — the audio is modified in place.
§Panics
Panics if the underlying storage is not contiguous in memory. Use
AudioSamples::try_apply_to_channel_data to handle non-contiguous inputs
without panicking.
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
let mut audio = AudioSamples::new_mono(
array![1.0f32, 2.0, 3.0, 4.0],
sample_rate!(44100),
).unwrap();
// Add 10.0 to every sample.
audio.apply_to_channel_data(|_ch, samples| {
for s in samples { *s += 10.0; }
});
assert_eq!(audio.as_mono().unwrap(), &array![11.0f32, 12.0, 13.0, 14.0]);Sourcepub fn apply_to_windows<F>(&mut self, window_size: usize, hop_size: usize, f: F)
pub fn apply_to_windows<F>(&mut self, window_size: usize, hop_size: usize, f: F)
Applies a mutable function to each temporal window of audio data.
For mono audio, the callback receives a mutable slice directly into the
underlying buffer for each window. For multi-channel audio, the callback
receives a temporary interleaved buffer of length window_size * num_channels
laid out as [ch0_s0, ch1_s0, …, ch0_s1, ch1_s1, …]; changes are
written back into the underlying storage after the callback returns.
Only fully-contained windows are visited; trailing samples that do not form a complete window are not passed to the callback.
Use this method for in-place windowed processing, such as applying window
functions or block-wise gain changes, when the read-only
[AudioSamples::windows] iterator is not sufficient.
§Arguments
– window_size — number of samples per channel in each window. If zero,
the method returns immediately.
– hop_size — number of samples to advance between window starts. If zero,
the method returns immediately.
– f — a closure of the form FnMut(window_index: usize, window_samples: &mut [T]).
– window_index — zero-based index of the current window.
– window_samples — mutable slice for the current window. For mono audio,
length equals window_size. For multi-channel audio, length equals
window_size * num_channels, laid out in interleaved channel order.
§Returns
() — the audio is modified in place.
§Panics
Does not panic.
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
let mut audio = AudioSamples::new_mono(
array![1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0],
sample_rate!(44100),
).unwrap();
// Halve every sample using non-overlapping windows of size 3.
audio.apply_to_windows(3, 3, |_window_idx, window| {
for s in window { *s *= 0.5; }
});
assert_eq!(
audio.as_mono().unwrap(),
&array![0.5f32, 1.0, 1.5, 2.0, 2.5, 3.0],
);Sourcepub fn borrow(&self) -> AudioSamples<'_, T>
pub fn borrow(&self) -> AudioSamples<'_, T>
Borrows the audio data as an AudioSamples with the same lifetime.
Sourcepub fn as_vec(&self) -> Vec<T>
pub fn as_vec(&self) -> Vec<T>
Returns all samples as a Vec<T>.
For mono audio the vec contains samples_per_channel elements. For multi-channel
audio the samples are in row-major order: all samples for channel 0, then channel 1, etc.
This always allocates a new Vec.
§Returns
A Vec<T> containing every sample.
Sourcepub fn is_standard_layout(&self) -> bool
pub fn is_standard_layout(&self) -> bool
Returns true if the underlying ndarray buffer uses standard (C/row-major) memory layout.
Some low-level operations (raw pointer access, SIMD paths) require standard layout.
§Returns
true if the storage is contiguous and row-major, false otherwise.
Sourcepub fn convert_to<O>(&self) -> AudioSamples<'static, O>
pub fn convert_to<O>(&self) -> AudioSamples<'static, O>
Convert audio samples to another sample type.
§Returns
A new AudioSamples instance with the same audio data converted to type O. The conversion is performed element-wise using the ConvertTo and ConvertFrom traits. This always allocates a new buffer for the converted samples.
Sourcepub fn to_interleaved_vec(&self) -> NonEmptyVec<T>
pub fn to_interleaved_vec(&self) -> NonEmptyVec<T>
Convert the AudioSamples struct into a vector of samples in interleaved format.
Sourcepub fn total_frames(&self) -> NonZeroUsize
pub fn total_frames(&self) -> NonZeroUsize
Returns the number of frames (time steps) in the audio.
A frame contains one sample per channel. For mono audio this equals
samples_per_channel(). For multi-channel audio it equals samples_per_channel().
§Returns
The total number of frames as a non-zero usize.
Sourcepub fn as_slice(&self) -> Option<&[T]>
pub fn as_slice(&self) -> Option<&[T]>
Returns a slice of the audio samples if the data is contiguous. None otherwise
§Returns
Some(&[T]) if the audio data is stored contiguously in memory, otherwise None.
Sourcepub fn as_slice_mut(&mut self) -> Option<&mut [T]>
pub fn as_slice_mut(&mut self) -> Option<&mut [T]>
Returns a mutable slice of the audio samples if the data is contiguous. None otherwise
§Returns
Some(&mut [T]) if the audio data is stored contiguously in memory, otherwise None.
Sourcepub fn info(&self) -> (NonZeroU32, NonZeroUsize, f64, NonZeroU32)
pub fn info(&self) -> (NonZeroU32, NonZeroUsize, f64, NonZeroU32)
Returns basic info: (num_channels, samples_per_channel, duration_seconds, sample_rate, layout)
§Returns
A tuple containing the number of channels, the number of samples per channel, the duration in seconds, and the sample rate.
Sourcepub fn sample_rate(&self) -> NonZeroU32
pub 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)).unwrap();
assert_eq!(audio.sample_rate().get(), 44100);Sourcepub fn sample_rate_hz(&self) -> f64
pub fn sample_rate_hz(&self) -> f64
Returns the sample rate as a plain f64.
This is a convenience method equivalent to self.sample_rate().get().
Sourcepub fn num_channels(&self) -> NonZeroU32
pub fn num_channels(&self) -> NonZeroU32
Returns the number of channels.
This is guaranteed to be ≥ 1 by construction.
Sourcepub fn samples_per_channel(&self) -> NonZeroUsize
pub fn samples_per_channel(&self) -> NonZeroUsize
Returns the number of samples per channel.
This is guaranteed to be ≥ 1 by construction (empty audio is not allowed).
Sourcepub fn duration_seconds(&self) -> f64
pub fn duration_seconds(&self) -> f64
Returns the duration in seconds
Sourcepub fn total_samples(&self) -> NonZeroUsize
pub fn total_samples(&self) -> NonZeroUsize
Returns the total number of samples across all channels
Sourcepub fn bytes_per_sample(&self) -> NonZeroU32
pub fn bytes_per_sample(&self) -> NonZeroU32
Returns the number of bytes per sample for type T
Sourcepub fn is_multi_channel(&self) -> bool
pub fn is_multi_channel(&self) -> bool
Returns true if this is multi-channel audio
Sourcepub fn len(&self) -> NonZeroUsize
pub fn len(&self) -> NonZeroUsize
Returns the total number of samples.
Sourcepub fn apply<F>(&mut self, f: F)where
F: Fn(T) -> T,
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));Sourcepub fn apply_to_channels<F>(&mut self, channels: &[u32], f: F)
pub fn apply_to_channels<F>(&mut self, channels: &[u32], f: F)
Apply a function to specific channels.
Sourcepub fn map<F>(&self, f: F) -> AudioSamples<'static, T>where
F: Fn(T) -> T,
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));Sourcepub fn map_into<O, F>(&self, f: F) -> AudioSamples<'static, O>
pub fn map_into<O, F>(&self, f: F) -> AudioSamples<'static, 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.
Sourcepub fn apply_with_index<F>(&mut self, f: F)
pub fn apply_with_index<F>(&mut self, f: F)
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
});Sourcepub fn slice_samples<R>(
&self,
sample_range: R,
) -> AudioSampleResult<AudioSamples<'_, T>>
pub fn slice_samples<R>( &self, sample_range: R, ) -> AudioSampleResult<AudioSamples<'_, T>>
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.
Sourcepub fn slice_channels<'iter, R>(
&'iter self,
channel_range: R,
) -> AudioSampleResult<AudioSamples<'static, T>>
pub fn slice_channels<'iter, R>( &'iter self, channel_range: R, ) -> AudioSampleResult<AudioSamples<'static, T>>
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.
Sourcepub fn slice_both<CR, SR>(
&self,
channel_range: CR,
sample_range: SR,
) -> AudioSampleResult<AudioSamples<'static, T>>
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 extractsample_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.
Sourcepub fn bytes(&self) -> AudioSampleResult<AudioBytes<'_>>
pub fn bytes(&self) -> AudioSampleResult<AudioBytes<'_>>
Returns a contiguous byte view when possible.
§Errors
- If the audio data is not stored contiguously in memory, an error is returned since a byte view cannot be created.
Sourcepub fn into_bytes(&self) -> AudioSampleResult<NonEmptyByteVec>
pub fn into_bytes(&self) -> AudioSampleResult<NonEmptyByteVec>
Convert audio samples to raw bytes. If the underlying data is not contiguous, this will return an error
§Errors
- If the audio data is not stored contiguously in memory, an error is returned since a byte view cannot be created.
Sourcepub fn total_byte_size(&self) -> NonZeroUsize
pub fn total_byte_size(&self) -> NonZeroUsize
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, sample_rate};
use ndarray::array;
let audio = AudioSamples::new_mono(array![1.0f32, 2.0, 3.0], sample_rate!(44100)).unwrap();
assert_eq!(audio.total_byte_size().get(), 12); // 3 samples × 4 bytes per f32Sourcepub fn apply_windowed<F>(
&mut self,
window_size: NonZeroUsize,
hop_size: NonZeroUsize,
func: F,
) -> AudioSampleResult<()>
pub fn apply_windowed<F>( &mut self, window_size: NonZeroUsize, hop_size: NonZeroUsize, func: F, ) -> AudioSampleResult<()>
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 sampleshop_size- Number of samples to advance between windowsfunc- Function called for each window, receiving(current_window, prev_window)
§Returns
Returns Ok(()) on success, or an error if parameters are invalid.
§Errors
- If the underlying array data cannot be accessed contiguously
Sourcepub fn replace_data(
&mut self,
new_data: AudioData<'a, T>,
) -> AudioSampleResult<()>
pub fn replace_data( &mut self, new_data: AudioData<'a, T>, ) -> AudioSampleResult<()>
Replaces the audio data while preserving sample rate.
This method allows you to swap out the underlying audio data with new data of the same channel configuration, maintaining the existing sample rate.
§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
ParameterErrorif the new data has a different number of channels
§Examples
use audio_samples::{AudioSamples, AudioData, sample_rate};
use ndarray::array;
// Create initial audio
let initial_data = array![1.0f32, 2.0, 3.0];
let mut audio = AudioSamples::new_mono(initial_data, sample_rate!(44100)).unwrap();
// Replace with new data
let new_data = AudioData::new_mono(array![4.0f32, 5.0, 6.0, 7.0]).unwrap();
audio.replace_data(new_data)?;
assert_eq!(audio.samples_per_channel().get(), 4);
assert_eq!(audio.sample_rate().get(), 44100); // PreservedSourcepub fn replace_with_mono(&mut self, data: Array1<T>) -> AudioSampleResult<()>
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
ParameterErrorif the current audio is not mono
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
// Create initial mono audio
let mut audio = AudioSamples::new_mono(array![1.0f32, 2.0], sample_rate!(44100)).unwrap();
// Replace with new mono data
audio.replace_with_mono(array![3.0f32, 4.0, 5.0])?;
assert_eq!(audio.samples_per_channel().get(), 3);
assert_eq!(audio.sample_rate().get(), 44100); // PreservedSourcepub fn replace_with_multi(&mut self, data: Array2<T>) -> AudioSampleResult<()>
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
ParameterErrorif the current audio is mono - Returns
ParameterErrorif the new data has different number of channels
§Examples
use audio_samples::{AudioSamples, sample_rate};
use ndarray::array;
// Create initial stereo audio
let mut audio = AudioSamples::new_multi_channel(
array![[1.0f32, 2.0], [3.0, 4.0]], sample_rate!(44100)
).unwrap();
// 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().get(), 3);
assert_eq!(audio.num_channels().get(), 2);
assert_eq!(audio.sample_rate().get(), 44100); // PreservedSourcepub fn replace_with_vec(
&mut self,
samples: &NonEmptyVec<T>,
) -> AudioSampleResult<()>
pub fn replace_with_vec( &mut self, samples: &NonEmptyVec<T>, ) -> AudioSampleResult<()>
Replaces the audio data with new data from a Vec.
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
ParameterErrorif the sample count is not divisible by current channel count - Returns
ParameterErrorif the resulting array cannot be created
§Examples
use audio_samples::{AudioSamples, sample_rate};
use non_empty_slice::non_empty_vec;
use ndarray::array;
// Replace mono audio
let mut mono_audio = AudioSamples::new_mono(array![1.0f32, 2.0], sample_rate!(44100)).unwrap();
mono_audio.replace_with_vec(&non_empty_vec![3.0f32, 4.0, 5.0, 6.0])?;
assert_eq!(mono_audio.samples_per_channel().get(), 4);
// Replace stereo audio (interleaved samples)
let mut stereo_audio = AudioSamples::new_multi_channel(
array![[1.0f32, 2.0], [3.0, 4.0]], sample_rate!(44100)
).unwrap();
stereo_audio.replace_with_vec(&non_empty_vec![5.0f32, 6.0, 7.0, 8.0, 9.0, 10.0])?;
assert_eq!(stereo_audio.samples_per_channel().get(), 3); // 6 samples ÷ 2 channels
assert_eq!(stereo_audio.num_channels().get(), 2);Sourcepub fn replace_with_vec_channels(
&mut self,
samples: &NonEmptyVec<T>,
expected_channels: NonZeroU32,
) -> AudioSampleResult<()>
pub fn replace_with_vec_channels( &mut self, samples: &NonEmptyVec<T>, expected_channels: NonZeroU32, ) -> 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 dataexpected_channels- Expected number of channels for validation
§Returns
Returns Ok(()) on success, or an error if validation fails.
§Errors
- Returns
ParameterErrorif the sample count is not divisible byexpected_channels - Returns
ParameterErrorif the current audio doesn’t matchexpected_channels - Returns
ParameterErrorif the resulting array cannot be created
§Examples
use audio_samples::{AudioSamples, sample_rate, channels};
use non_empty_slice::non_empty_vec;
use ndarray::array;
// Create placeholder stereo audio
let mut audio = AudioSamples::new_multi_channel(
array![[0.0f32, 0.0], [0.0, 0.0]], sample_rate!(44100)
).unwrap();
// Replace with data that must be stereo (2 channels)
let samples = non_empty_vec![1.0f32, 2.0, 3.0, 4.0]; // 4 samples = 2 samples per channel
audio.replace_with_vec_channels(&samples, channels!(2))?;
assert_eq!(audio.samples_per_channel().get(), 2);
assert_eq!(audio.num_channels().get(), 2);Sourcepub fn as_mono(&self) -> Option<&MonoData<'a, T>>
pub 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.
Sourcepub fn as_multi_channel(&self) -> Option<&MultiData<'a, T>>
pub 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.
Sourcepub fn as_mono_mut(&mut self) -> Option<&mut MonoData<'a, T>>
pub 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.
Sourcepub fn as_multi_channel_mut(&mut self) -> Option<&mut MultiData<'a, T>>
pub 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.
Sourcepub fn with_window_mut<R>(
&mut self,
start: usize,
len: NonZeroUsize,
f: impl FnOnce(WindowMut<'_, T>) -> R,
) -> Option<R>
pub fn with_window_mut<R>( &mut self, start: usize, len: NonZeroUsize, f: impl FnOnce(WindowMut<'_, T>) -> R, ) -> Option<R>
Calls f with a mutable view of the window.
For mono: ArrayViewMut1<T> of length len.
For multi: ArrayViewMut2<T> with shape:
- (channels, len) if SamplesAreAxis1
- (len, channels) if SamplesAreAxis0
Trait Implementations§
Source§impl<'a, T> AsMut<AudioSamples<'a, T>> for StereoAudioSamples<'a, T>where
T: StandardSample,
Provides a mutable reference to the inner AudioSamples.
impl<'a, T> AsMut<AudioSamples<'a, T>> for StereoAudioSamples<'a, T>where
T: StandardSample,
Provides a mutable reference to the inner AudioSamples.
Source§fn as_mut(&mut self) -> &mut AudioSamples<'a, T>
fn as_mut(&mut self) -> &mut AudioSamples<'a, T>
Source§impl<'a, T> AsRef<AudioSamples<'a, T>> for StereoAudioSamples<'a, T>where
T: StandardSample,
Provides a shared reference to the inner AudioSamples.
impl<'a, T> AsRef<AudioSamples<'a, T>> for StereoAudioSamples<'a, T>where
T: StandardSample,
Provides a shared reference to the inner AudioSamples.
Source§fn as_ref(&self) -> &AudioSamples<'a, T>
fn as_ref(&self) -> &AudioSamples<'a, T>
Source§impl<'a, T> Deref for StereoAudioSamples<'a, T>where
T: StandardSample,
Provides transparent read access to the inner AudioSamples.
impl<'a, T> Deref for StereoAudioSamples<'a, T>where
T: StandardSample,
Provides transparent read access to the inner AudioSamples.
Source§impl<T> DerefMut for StereoAudioSamples<'_, T>where
T: StandardSample,
Provides transparent write access to the inner AudioSamples.
impl<T> DerefMut for StereoAudioSamples<'_, T>where
T: StandardSample,
Provides transparent write access to the inner AudioSamples.
Note: mutating the inner AudioSamples (e.g. via replace_data) can potentially
violate the stereo invariant. Prefer using StereoAudioSamples methods directly.
Source§impl<T> From<StereoAudioSamples<'static, T>> for AudioSamples<'static, T>where
T: StandardSample,
Unwraps a StereoAudioSamples back into the underlying AudioSamples.
impl<T> From<StereoAudioSamples<'static, T>> for AudioSamples<'static, T>where
T: StandardSample,
Unwraps a StereoAudioSamples back into the underlying AudioSamples.
Source§fn from(stereo: StereoAudioSamples<'static, T>) -> Self
fn from(stereo: StereoAudioSamples<'static, T>) -> Self
Source§impl<T> TryFrom<AudioSamples<'static, T>> for StereoAudioSamples<'static, T>where
T: StandardSample,
Zero-copy conversion from an owned AudioSamples into a StereoAudioSamples.
impl<T> TryFrom<AudioSamples<'static, T>> for StereoAudioSamples<'static, T>where
T: StandardSample,
Zero-copy conversion from an owned AudioSamples into a StereoAudioSamples.
§Errors
Returns crate::AudioSampleError::Parameter if the audio does not have exactly 2 channels.
Source§type Error = AudioSampleError
type Error = AudioSampleError
Auto Trait Implementations§
impl<'a, T> Freeze for StereoAudioSamples<'a, T>
impl<'a, T> RefUnwindSafe for StereoAudioSamples<'a, T>where
T: RefUnwindSafe,
impl<'a, T> Send for StereoAudioSamples<'a, T>
impl<'a, T> Sync for StereoAudioSamples<'a, T>
impl<'a, T> Unpin for StereoAudioSamples<'a, T>
impl<'a, T> UnsafeUnpin for StereoAudioSamples<'a, T>
impl<'a, T> !UnwindSafe for StereoAudioSamples<'a, T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<Src, Dst> ConvertTo<Dst> for Srcwhere
Dst: ConvertFrom<Src>,
impl<Src, Dst> ConvertTo<Dst> for Srcwhere
Dst: ConvertFrom<Src>,
Source§fn convert_to(self) -> Dst
fn convert_to(self) -> Dst
Dst using audio-aware scaling. Read more