Crate phonic

Crate phonic 

Source
Expand description

phonic is a cross-platform audio playback and DSP library for Rust. It provides a flexible, low-latency audio engine and DSP tools for desktop and web applications.

§Overview

  • Player is the central component that manages audio playback. It takes an output device instance, plays sounds and manages DSP effects.

  • OutputDevice represents the audio backend stream. phonic provides implementations for different platforms, such as cpal for native applications and web-audio for WebAssembly.

  • Source produces audio signals. You can use the built-in FileSource for playing back one-shot audio files, SynthSource for generating synthesized one-shot tones, or create your own custom source implementation. Files can be played preloaded from RAM or streamed on-the-fly.

  • Generator is a source that plays sounds driven by note and parameter events. Use e.g. a Sampler to play back sample files with optional AHDSR envelopes, or FunDspGenerator to create a custom synth via fundsp, or create your own custom generator.

  • Effect applies DSP effects to audio signals in a mixer and describes its automatable properties via Parameters. Phonic comes with a basic set of effects, but you can create your own custom ones too. Effects are applied within mixers. By default, the player includes one main mixer that routes all sources through it. For more complex audio routing, create additional mixers using Player::add_mixer and route specific sources to them.

§Getting Started

Here’s a basic example of how to play audio files with DSP effects.

use std::time::Duration;

use phonic::{
    DefaultOutputDevice, Player, FilePlaybackOptions, Error,
    effects::{ChorusEffect, ReverbEffect, CompressorEffect},
    generators::Sampler, GeneratorPlaybackOptions,
};

fn main() -> Result<(), Error> {
    // Create a player with the default audio output device.
    let mut player = Player::new(DefaultOutputDevice::open()?, None);

    // Store some constants for event scheduling.
    let now = player.output_sample_frame_position();
    let samples_per_sec = player.output_sample_rate() as u64;

    // Add a new sub-mixer with a chorus and reverb effect to the main mixer.
    let sub_mixer = {
        let new_mixer = player.add_mixer(None)?;
        player.add_effect(ChorusEffect::default(), new_mixer.id())?;
        player.add_effect(ReverbEffect::default(), new_mixer.id())?;
        new_mixer
    };

    // Add a limiter to the main mixer. All sounds, including the sub mixer's output,
    // will be routed through this effect now.
    let limiter = player.add_effect(CompressorEffect::new_limiter(), None)?;

    // Change effect parameters via the returned handles.
    // Schedule a parameter change 3 seconds from now (sample-accurate).
    limiter.set_parameter(
        CompressorEffect::MAKEUP_GAIN.value_update(3.0),
        now + 3 * samples_per_sec
    );

    // Play a file and get a handle to control it.
    let file = player.play_file("path/to/your/file.wav",
      FilePlaybackOptions::default().target_mixer(sub_mixer.id())
    )?;

    // Control playback via the returned handles.
    // Schedule a stop 2 seconds from now (sample-accurate)
    file.stop(now + 2 * samples_per_sec)?;

    // Play another file on the main mixer with scheduled start time.
    let some_other_file = player.play_file("path/to/your/some_other_file.wav",
      FilePlaybackOptions::default().start_at_time(now + 2 * samples_per_sec)
    )?;

    // Create a sampler generator to play a sample.
    // We configure it to play on the sub-mixer.
    let generator = player.play_generator(
        Sampler::from_file(
            "path/to/instrument_sample.wav",
            None,
            GeneratorPlaybackOptions::default().target_mixer(sub_mixer.id()),
            player.output_channel_count(),
            player.output_sample_rate(),
        )?,
        None
     )?;

    // Trigger a note on the generator. The `generator` handle is `Send + Sync`, so you
    // can also pass it to other threads (e.g. a MIDI thread) to trigger events from there.
    generator.note_on(60, Some(1.0), None, None)?;

    // The player's audio output stream runs on a separate thread. Keep the
    // main thread running here, until all files finished playing.
    while file.is_playing() || some_other_file.is_playing() {
        std::thread::sleep(Duration::from_millis(100));
    }

    Ok(())
}

For more advanced usage, such as monitoring playback, sequencing playback, using generator and creating more complex mixer graphs, please see the examples in the README.md and the /examples directory of the repository.

Re-exports§

pub use four_cc;
pub use fundsp;fundsp

Modules§

effects
Set of basic, common DSP Effect implementations.
generators
Set of basic, common Generator source implementations.
outputs
Default OutputDevice implementations.
parameters
Effect Parameter implementations.
sources
Set of basic, common File & Synth tone Source implementations.
utils
DSP tools, musical unit conversion functions and related UI tools.

Structs§

CpuLoad
CPU load of a playing source, typically accessed via the source’s playback handle.
EffectHandle
Automate Effect parameters or send messages.
FilePlaybackHandle
Query and change runtime playback properties of a playing FileSource.
FilePlaybackOptions
Options to control playback properties of a FileSource.
GeneratorPlaybackHandle
Query and change runtime playback properties of a playing Generator.
GeneratorPlaybackOptions
Options for playing back a generator source.
MixerHandle
A handle to a mixer, which allows querying runtime properties.
Player
Playback controller, which continuously fills an OutputDevices stream with audio data generated by one or more Sources.
SourceTime
Timing info for Source impls.
SynthPlaybackHandle
Query and change runtime playback properties of a playing SynthSource.
SynthPlaybackOptions
Options to control playback properties of a SynthSource.

Enums§

EffectMovement
How to move an effect within a mixer.
Error
Provides an enumeration of all possible errors reported by phonic.
GeneratorPlaybackEvent
Events to start/stop, change playback properties or parameters within a Generator.
GeneratorPlaybackMessage
Messages to control playback of and within a Generator.
ParameterPolarity
Describes polarity of a Parameter for visual representations in a UI.
ParameterScaling
Effect parameter scaling for float parameters, applied to convert normalized UI or automation values to the internal values.
ParameterType
Describes the type of a Parameter to e.g. select a proper visual representation in a UI.
ParameterValueUpdate
An update for a Parameter’s value, consumed by Effects or Generator in audio time.
PlaybackStatusEvent
Events send back from File or Synth sources via the player to the user.
ResamplingQuality
The resampler quality an audio source can be resampled with.
SourcePlaybackHandle
A unified FilePlaybackHandle and SynthPlaybackHandle.
SynthPlaybackMessage
Events to control playback of a SynthSource

Traits§

Effect
DSP effect that processes audio signals within a mixer’s effect chain.
EffectMessage
Carries Effect-specific payloads/automation, which can’t or should not be expressed as Parameter.
FileSource
A source which decodes and plays back an audio file.
Generator
A Source that is driven by note events.
OutputDevice
Audio output stream device backend.
Parameter
Describes a single parameter in an Effect or Generator.
Source
Audio signal producer that generates new or processes existing audio samples.
SynthSource
A Source which creates samples from a synthesized signal.

Type Aliases§

DefaultOutputDevicecpal-output or web-output
The enabled audio output type: cpal or web
EffectId
Unique ID for newly added effects.
EffectMessagePayload
Type used in Effect::process_message to receive messages.
EffectTime
Frame and wall-clock time reference for an audio effect’s process function.
MixerId
Unique mixer ID for newly added mixers.
NotePlaybackId
Unique ID for individual sounds played in a generator.
PanicHandler
A callback function to handle panics occurring within the player’s main mixer.
PlaybackId
Unique source ID for played back file, synth or generator sources.
PlaybackStatusContext
Custom context type for playback status events.