Struct babycat::Waveform

source ·
pub struct Waveform { /* private fields */ }
Expand description

Represents a fixed-length audio waveform as a Vec<f32>.

Implementations§

source§

impl Waveform

source

pub fn from_interleaved_samples( frame_rate_hz: u32, num_channels: u16, interleaved_samples: &[f32] ) -> Self

source

pub fn from_source( args: WaveformArgs, source: Box<dyn Source + '_> ) -> Result<Self, Error>

source

pub fn from_encoded_bytes( encoded_bytes: &[u8], waveform_args: WaveformArgs ) -> Result<Self, Error>

Decodes audio stored in an in-memory byte array.

Arguments
  • encoded_bytes: A byte array containing encoded (e.g. MP3) audio.
  • waveform_args: Instructions on how to decode the audio.
Examples
use babycat::assertions::assert_debug;
use babycat::Waveform;

let encoded_bytes: Vec<u8> = std::fs::read("audio-for-tests/andreas-theme/track.flac").unwrap();

let waveform_args = Default::default();

let waveform = Waveform::from_encoded_bytes(
    &encoded_bytes,
    waveform_args,
).unwrap();
assert_debug(
    &waveform,
    "Waveform { 9586415 frames,  2 channels,  44100 hz,  3m 37s 379ms }",
);
source

pub fn from_encoded_bytes_with_hint( encoded_bytes: &[u8], waveform_args: WaveformArgs, file_extension: &str, mime_type: &str ) -> Result<Self, Error>

Decodes audio in an in-memory byte array, using user-specified encoding hints.

Arguments
  • encoded_bytes: A byte array containing encoded (e.g. MP3) audio.
  • waveform_args: Instructions on how to decode the audio.
  • file_extension: A hint–in the form of a file extension–to indicate the encoding of the audio in encoded_bytes.
  • mime_type: A hint–in the form of a MIME type–to indicate the encoding of the audio in encoded_bytes.
source

pub fn from_file( filename: &str, waveform_args: WaveformArgs ) -> Result<Self, Error>

Decodes audio stored in a locaselect_first_channelsl file.

Arguments
  • filename: A filename of an encoded audio file on the local filesystem.
  • waveform_args: Instructions on how to decode the audio.
Feature flags

This function is only available if the Cargo feature enable-fileystem flag is enabled. The enable-filesystem flag is enabled by default for the Babycat’s Rust, Python, and C frontends, but is disabled for the WebAssembly frontend.

Examples

Decode one audio file with the default decoding arguments:

use babycat::{assertions::assert_debug, WaveformArgs, Waveform};

let waveform = Waveform::from_file(
   "audio-for-tests/circus-of-freaks/track.flac",
    Default::default(),
).unwrap();

assert_debug(
    &waveform,
    "Waveform { 2491247 frames,  2 channels,  44100 hz,  56s 490ms }",
);

Decode only the first 30 seconds and upsample to 48khz:

use babycat::{assertions::assert_debug, WaveformArgs, Waveform};

let waveform_args = WaveformArgs {
    end_time_milliseconds: 30000,
    frame_rate_hz: 48000,
    ..Default::default()
};
let waveform = Waveform::from_file(
   "audio-for-tests/circus-of-freaks/track.flac",
    waveform_args,
).unwrap();

assert_debug(
    &waveform,
    "Waveform { 1440000 frames,  2 channels,  48000 hz,  30s }"    
);
source

pub fn from_encoded_stream<R: 'static + Read + Send + Sync>( encoded_stream: R, waveform_args: WaveformArgs ) -> Result<Self, Error>

Decodes audio from an input stream.

Waveform will take ownership of the stream and read it until the end. Therefore, you cannot provide an infinte-length stream.

Arguments
  • encoded_stream: An I/O stream of encoded audio to decode.
  • waveform_args: Instructions on how to decode the audio.
source

pub fn from_encoded_stream_with_hint<R: 'static + Read + Send + Sync>( encoded_stream: R, waveform_args: WaveformArgs, file_extension: &str, mime_type: &str ) -> Result<Self, Error>

Decodes audio from an input stream, using a user-specified decoding hint.

Arguments
  • encoded_stream: An I/O stream of encoded audio to decode.
  • waveform_args: Instructions on how to decode the audio.
  • file_extension: A hint–in the form of a file extension–to indicate the encoding of the audio in encoded_bytes.
  • mime_type: A hint–in the form of a MIME type–to indicate the encoding of the audio in encoded_bytes.
source

pub fn from_frames_of_silence( frame_rate_hz: u32, num_channels: u16, num_frames: usize ) -> Self

Creates a silent waveform measured in frames.

Arguments
  • frame_rate_hz: The frame rate of the waveform to create.
  • num_channels: The number of channels in the waveform to create.
  • num_frames: The number of frames of audio to generate.
Examples

This creates a Waveform containing one second of silent stereo audio.

use babycat::Waveform;
use babycat::assertions::assert_debug;

let waveform = Waveform::from_frames_of_silence(44100, 2, 44100);
assert_debug(
    &waveform,
    "Waveform { 44100 frames,  2 channels,  44100 hz,  1s }"
);
source

pub fn from_milliseconds_of_silence( frame_rate_hz: u32, num_channels: u16, duration_milliseconds: usize ) -> Self

Create a silent waveform measured in milliseconds.

Arguments
  • frame_rate_hz: The frame rate of the waveform to create.
  • num_channels: The number of channels in the waveform to create.
  • duration_milliseconds: The length of the audio waveform in milliseconds.
Examples

This creates a Waveform containing one second of silent stereo audio.

use babycat::Waveform;
use babycat::assertions::assert_debug;

let waveform = Waveform::from_milliseconds_of_silence(44100, 2, 1000);
assert_debug(
    &waveform,
    "Waveform { 44100 frames,  2 channels,  44100 hz,  1s }",
);
source

pub fn resample(&self, frame_rate_hz: u32) -> Result<Self, Error>

Resamples the waveform using the default resampler.

Arguments
  • frame_rate_hz: The destination frame rate to resample to.
Examples
use babycat::{assertions::assert_debug, Waveform};

let waveform = Waveform::from_file(
    "audio-for-tests/circus-of-freaks/track.flac",
    Default::default()
).unwrap();
assert_debug(
   &waveform,
   "Waveform { 2491247 frames,  2 channels,  44100 hz,  56s 490ms }"
);

let upsampled = waveform.resample(96000).unwrap();
assert_debug(
    &upsampled,
    "Waveform { 5423123 frames,  2 channels,  96000 hz,  56s 490ms }"
);

let downsampled = waveform.resample(8252).unwrap();
assert_debug(
    &downsampled,
    "Waveform { 466163 frames,  2 channels,  8252 hz,  56s 490ms }",
);
source

pub fn resample_by_mode( &self, frame_rate_hz: u32, resample_mode: u32 ) -> Result<Self, Error>

Resamples the audio using a specific resampler.

Arguments
  • frame_rate_hz: The destination frame rate to resample to.
  • resample_mode: The Babycat resampling backend to pick.
Examples
use babycat::{assertions::assert_debug, Waveform};

let waveform = Waveform::from_file(
    "audio-for-tests/circus-of-freaks/track.flac",
    Default::default()
).unwrap();
assert_debug(
    &waveform,
    "Waveform { 2491247 frames,  2 channels,  44100 hz,  56s 490ms }",
);

// Here we upsample our audio to 96khz with the libsamplerate resampler.
let upsampled_libsamplerate = waveform.resample_by_mode(
    96000,
    babycat::constants::RESAMPLE_MODE_LIBSAMPLERATE
).unwrap();
assert_debug(
    &upsampled_libsamplerate,
    "Waveform { 5423123 frames,  2 channels,  96000 hz,  56s 490ms }",
);

// And we upsample our audio again with Babycat's Lanczos resampler.
let upsampled_lanczos = waveform.resample_by_mode(
    96000,
    babycat::constants::RESAMPLE_MODE_BABYCAT_LANCZOS
).unwrap();
assert_debug(
    &upsampled_lanczos,
    "Waveform { 5423123 frames,  2 channels,  96000 hz,  56s 490ms }",
);
source

pub fn to_wav_buffer(&self) -> Result<Vec<u8>, Error>

Encodes the waveform into a WAV-encoded byte array.

source

pub fn to_wav_file(&self, filename: &str) -> Result<(), Error>

Writes the waveform to the filesystem as a WAV file.

Feature flags

This function is only available if the Cargo feature enable-fileystem flag is enabled. The enable-filesystem flag is enabled by default for the Babycat’s Rust, Python, and C frontends, but is disabled for the WebAssembly frontend.

source

pub fn new( frame_rate_hz: u32, num_channels: u16, interleaved_samples: Vec<f32> ) -> Self

Constructs a Waveform from an already-decoded vector of 32-bit float samples.

Arguments
  • frame_rate_hz:
  • num_channels:
  • interleaved_samples:
Examples

This creates a Waveform containing one second of silent stereo audio. Note that the input vector contains 88,200 audio samples–which we divide into 44,100 frames containing two samples each.

use babycat::Waveform;
use babycat::assertions::assert_debug;

let frame_rate_hz = 44100;
let num_channels = 2;
let raw_uncompressed_audio: Vec<f32> = vec![0.0_f32; 88200];
let waveform = Waveform::new(frame_rate_hz, num_channels, raw_uncompressed_audio);
assert_debug(
    &waveform,
    "Waveform { 44100 frames,  2 channels,  44100 hz,  1s }",
);
source

pub fn get_sample(&self, frame_idx: usize, channel_idx: u16) -> Option<f32>

Return a given audio sample belonging to a specific frame and channel.

This method performs bounds checks before returning an audio sample. If you want a method that does not perform bounds checks, use get_unchecked_sample.

Examples
use babycat::Waveform;

let interleaved_samples: Vec<f32> = vec![
   -1.0, -0.9, -0.8, //
   -0.7, -0.6, -0.5, //
   -0.4, -0.3, -0.2, //
   -0.1, 0.0, 0.1, //
   0.2, 0.3, 0.4,
];

let frame_rate_hz = 44100;
let num_channels = 3;

let waveform = Waveform::from_interleaved_samples(
    frame_rate_hz, num_channels, &interleaved_samples,
);

assert_eq!(waveform.get_sample(0, 0).unwrap(), -1.0);
assert_eq!(waveform.get_sample(0, 1).unwrap(), -0.9);
assert_eq!(waveform.get_sample(0, 2).unwrap(), -0.8);

assert_eq!(waveform.get_sample(1, 0).unwrap(), -0.7);
assert_eq!(waveform.get_sample(1, 1).unwrap(), -0.6);
assert_eq!(waveform.get_sample(1, 2).unwrap(), -0.5);
source

pub unsafe fn get_unchecked_sample( &self, frame_idx: usize, channel_idx: u16 ) -> f32

Return a given audio sample belonging to a specific frame and channel, without performing any bounds checks.

If you want a method that performs bounds checks, use get_sample.

Examples
use babycat::Waveform;

let interleaved_samples: Vec<f32> = vec![
   -1.0, -0.9, -0.8, //
   -0.7, -0.6, -0.5, //
   -0.4, -0.3, -0.2, //
   -0.1, 0.0, 0.1, //
   0.2, 0.3, 0.4,
];

let frame_rate_hz = 44100;
let num_channels = 3;

let waveform = Waveform::from_interleaved_samples(
    frame_rate_hz, num_channels, &interleaved_samples,
);

unsafe {
    assert_eq!(waveform.get_unchecked_sample(0, 0), -1.0);
    assert_eq!(waveform.get_unchecked_sample(0, 1), -0.9);
    assert_eq!(waveform.get_unchecked_sample(0, 2), -0.8);

    assert_eq!(waveform.get_unchecked_sample(1, 0), -0.7);
    assert_eq!(waveform.get_unchecked_sample(1, 1), -0.6);
    assert_eq!(waveform.get_unchecked_sample(1, 2), -0.5);
}
Safety

Because this method does not peform any bounds checks, it is unsafe.

source

pub fn get_interleaved_sample(&self, sample_idx: usize) -> Option<f32>

source

pub unsafe fn get_unchecked_interleaved_sample(&self, sample_idx: usize) -> f32

Safety

Because this method does not peform any bounds checks, it is unsafe.

source

pub fn num_samples(&self) -> usize

source

pub fn num_frames(&self) -> usize

Returns the total number of decoded frames in the Waveform.

source

pub fn to_interleaved_samples(&self) -> &[f32]

Returns the waveform as a slice of channel-interleaved f32 samples.

source

pub fn into_source(self) -> WaveformSource

Trait Implementations§

source§

impl Clone for Waveform

source§

fn clone(&self) -> Waveform

Returns a copy 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 Debug for Waveform

source§

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

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

impl<'de> Deserialize<'de> for Waveform

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl From<Waveform> for Vec<f32>

source§

fn from(waveform: Waveform) -> Vec<f32>

Converts to this type from the input type.
source§

impl From<Waveform> for WaveformSource

source§

fn from(waveform: Waveform) -> WaveformSource

Converts to this type from the input type.
source§

impl PartialEq<Waveform> for Waveform

source§

fn eq(&self, other: &Waveform) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

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

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Serialize for Waveform

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Signal for Waveform

source§

fn frame_rate_hz(&self) -> u32

Returns the frame rate of the Waveform.

source§

fn num_channels(&self) -> u16

Returns the number of channels in the Waveform.

source§

fn num_frames_estimate(&self) -> Option<usize>

An estimate of the total number of frames in the Signal.
source§

fn duration_estimate(&self) -> Option<Duration>

The wall-clock duration of this Signal, based on the estimated number of frames.
source§

fn duration_estimate_to_str(&self) -> String

A string representation of this Signal’s wall-clock duration.
source§

impl StructuralPartialEq for Waveform

Auto Trait Implementations§

Blanket Implementations§

source§

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

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

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

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

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

const: unstable · source§

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

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

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

const: unstable · 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.

§

impl<F, T> IntoSample<T> for Fwhere T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> ToOwned for Twhere T: Clone,

§

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, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

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

§

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

The type returned in the event of a conversion error.
const: unstable · source§

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

Performs the conversion.
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,