Skip to main content

Crate euphorium

Crate euphorium 

Source
Expand description

Euphorium: Painless audio playback for native and web platforms.

§Euphorium

Crates.io Version

Painless audio playback for native and web platforms.

A small Rust audio player built on top of rodio and CPAL.

§Installation

cargo add euphorium

§Usage

use euphorium::{Soundscape, SoundscapeError, SoundSource};

fn main() -> Result<(), SoundscapeError> {
    // One Soundscape owns the output and every sound in the application.
    let soundscape = Soundscape::new();
    let music = soundscape.create_group("music")?;
    let battle = music.create_group("battle")?;
    let theme = battle.create_sound("theme", SoundSource::file("audio.mp3"))?;

    // Group volume multiplies each descendant's local volume.
    music.set_volume(0.8)?;
    theme.set_volume(0.5)?;
    theme.set_speed(1.25)?;

    theme.play()?;
    theme.try_seek_secs(30.0)?;
    theme.wait_until_end()?;
    Ok(())
}

fn play_embedded_audio(audio: &'static [u8]) -> Result<(), SoundscapeError> {
    let soundscape = Soundscape::new();
    let sound = soundscape.create_sound("embedded", SoundSource::static_bytes(audio))?;
    sound.play()?;
    Ok(())
}

fn where_is_my_audio_at(soundscape: &Soundscape) -> Result<(), SoundscapeError> {
    let sound = soundscape.find_sound("music/battle/theme").expect("theme exists");
    sound.pause()?;
    sound.resume()?;
    println!("{} / {}", sound.position_formatted()?, sound.duration_formatted()?);
    Ok(())
}

fn play_my_audio_cross_platform() -> Result<(), SoundscapeError> {
    let soundscape = Soundscape::new();
    let sound = soundscape.create_sound(
        "music",
        euphorium::audio_source! {
            native: file("assets/music.mp3"),
            wasm: url("audio.mp3"),
        },
    )?;
    sound.play()?;

    // Call this from the application's update loop. It completes browser loads
    // and reports asynchronous failures for every sound in one place.
    for failure in soundscape.update() {
        eprintln!("sound {:?} failed: {}", failure.sound, failure.error);
    }
    Ok(())
}

// Define your application's sound keys in one place...
euphorium::sound_key! {
    enum AppSound {
        Music => "music",
        BattleTheme => "music/battle/theme",
    }
}

fn an_epic_scene(music: SoundSource, theme: SoundSource) -> Result<(), SoundscapeError> {
    let soundscape = Soundscape::<AppSound>::builder()
        .sound(AppSound::Music, music)
        .sound(AppSound::BattleTheme, theme)
        .build()?;

    // And now you get `Sound` instead of `Option<Sound>` for every key in `AppSound`.
    soundscape.sound(AppSound::BattleTheme).play()
}

Browsers require audio output to be opened in response to a user gesture. Start playback from a click, pointer, or keyboard event when possible.

Please find these examples for more guidance.

§Feature flags

FeatureEnables
cli (default)euphorium <PATH>
mp3 (default)MP3 decoding
flacFLAC decoding
mp4MP4 decoding
vorbisVorbis decoding
wav (default)WAV decoding
asioASIO backend
jackJACK backend
nightlyAudioWorklet backend

§Motivation

rodio and CPAL are both great libraries, but they are not very ergonomic to use. Here are some issues that I have encountered while using them:

  1. There is no Null backend, so you must forever live with Option<MixerDeviceSink>.
  2. rodio::Player::try_seek deadlocks on WASM and some specific threading setups.
  3. rodio seems to prioritize correctness, which is fine, but you end up needing to wrap a lot of code yourself to get predictable behavior e.g. setting time position or playback speed when no audio is playing.
  4. rodio does not officially support AudioWorklet while CPAL does.
  5. No convenience code in rodio for native and web audio resource handling, causing a ton of #[cfg(target_arch = "wasm32")].
  6. Concurrent playback requires callers to own and synchronize a collection of players.
  7. No Rayon support.
  8. No waveform visualization.

§License

Dual-licensed under the MIT License and the Apache License, Version 2.0. Choose whichever you prefer. This license only applies to Euphorium code.

By submitting a contribution, including code submitted through a pull request, you agree that your contribution will be dual-licensed under the MIT License and the Apache License, Version 2.0, without any additional terms or conditions.

Re-exports§

pub use sound::PlaybackEvent;
pub use sound::PlaybackState;
pub use self;
pub use cpal;

Modules§

decoder
Create a Decoder from various sources.
patch
Workarounds.
sound
Individual sound playback and control.
wsola
WSOLA time-stretching source for inputs with fixed channel count and sample rate.

Macros§

audio_source
Selects a native and WebAssembly source at compile time.
sound_key
Declares an enum implementing SoundKey.

Structs§

AutomaticGainEffect
Settings for rodio’s automatic gain control effect.
Device
An individual output device such as speakers, headphones, or a virtual device.
DistortionEffect
Settings for rodio’s distortion effect.
DopplerSettings
Controls global Doppler pitch shifting.
EmitterState
Emitter position and velocity in world space.
FilterEffect
Settings for a rodio low-pass or high-pass filter.
HrtfProfile
A shared head-related impulse response bank for binaural rendering.
LimiterEffect
Settings for rodio’s limiter effect.
ListenerState
Position, velocity, and orientation of the listener.
Occlusion
Direct-path transmission supplied by an application’s acoustic or geometry system.
Output
A cloneable handle to an audio output sink owned by a crate::Soundscape audio scene.
ReverbEffect
Settings for rodio’s reverb effect.
Sound
A playable sound owned by a Soundscape audio scene.
SoundEffects
Post-processing effects applied to newly played audio.
SoundError
An asynchronous sound failure discovered by Soundscape::update.
SoundGroup
A recursive mixer group owned by a Soundscape audio scene.
SoundGroupId
Identifies a sound group within one Soundscape instance.
SoundId
Identifies a sound within one Soundscape instance.
Soundscape
The root owner of an application’s audio scene.
SoundscapeBuilder
A validated constructor for a typed Soundscape scene.
SoundscapeEvent
A playback event emitted by one sound in a Soundscape instance.
SpatialAudioSettings
Scene-wide spatial rendering settings.
SpatialSound
Per-sound spatial rendering settings.
Waveform
A multiresolution amplitude overview of an audio track.
WaveformBuilder
An incrementally decoded waveform suitable for responsive user interfaces.
WaveformDecodeSummary
A summary of a streaming waveform decode.
WaveformPeak
The minimum and maximum sample amplitude in a section of an audio track.
WaveformPoll
Result of WaveformView::poll_visible and WaveformView::poll_visible_with_budget.
WaveformSlice
A borrowed, density-limited view into a Waveform.
WaveformView
Renderer-agnostic owner of waveform decoding and its visible window.

Enums§

DistanceAttenuation
Distance-based gain model for a point emitter.
HrtfError
Errors returned when loading an HRIR bank.
OutputError
An error that can occur while opening an audio backend or device.
SoundSource
An audio source assignment retained by a crate::Sound.
SoundscapeError
The error type for Euphorium operations.
SpatialInput
Selects how a sound’s channels are converted to a point emitter.
SpatialRenderer
Selects panning or HRTF convolution for spatial sounds.

Traits§

SoundKey
Declares the complete set of sounds that a typed Soundscape scene must contain.

Functions§

decode_audio_to_waveform_streaming
Decodes shared audio bytes into finest-resolution peak amplitudes in bounded chunks.
format_timestamp
Formats a Duration as a string in the format H:MM:SS or M:SS.
format_timestamp_secs
Formats f64 seconds as a string in the format H:MM:SS or M:SS.
parse_timestamp
Parses a timestamp string in the format H:MM:SS, M:SS, or SS into a number of seconds.
switch_outputs_to_backend
Convenience function to switch every output to one newly opened backend.
switch_outputs_to_device
Convenience function to switch every output to one newly opened output device.

Type Aliases§

Backend
A CPAL audio host that can provide an output device.