Expand description
Euphorium: Painless audio playback for native and web platforms.
§Euphorium
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
| Feature | Enables |
|---|---|
cli (default) | euphorium <PATH> |
mp3 (default) | MP3 decoding |
flac | FLAC decoding |
mp4 | MP4 decoding |
vorbis | Vorbis decoding |
wav (default) | WAV decoding |
asio | ASIO backend |
jack | JACK backend |
nightly | AudioWorklet 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:
- There is no Null backend, so you must forever live with
Option<MixerDeviceSink>. rodio::Player::try_seekdeadlocks on WASM and some specific threading setups.- 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.
- rodio does not officially support AudioWorklet while CPAL does.
- No convenience code in rodio for native and web audio resource handling, causing a ton of
#[cfg(target_arch = "wasm32")]. - Concurrent playback requires callers to own and synchronize a collection of players.
- No Rayon support.
- 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
Decoderfrom 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§
- Automatic
Gain Effect - Settings for rodio’s automatic gain control effect.
- Device
- An individual output device such as speakers, headphones, or a virtual device.
- Distortion
Effect - Settings for rodio’s distortion effect.
- Doppler
Settings - Controls global Doppler pitch shifting.
- Emitter
State - Emitter position and velocity in world space.
- Filter
Effect - Settings for a rodio low-pass or high-pass filter.
- Hrtf
Profile - A shared head-related impulse response bank for binaural rendering.
- Limiter
Effect - Settings for rodio’s limiter effect.
- Listener
State - 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::Soundscapeaudio scene. - Reverb
Effect - Settings for rodio’s reverb effect.
- Sound
- A playable sound owned by a
Soundscapeaudio scene. - Sound
Effects - Post-processing effects applied to newly played audio.
- Sound
Error - An asynchronous sound failure discovered by
Soundscape::update. - Sound
Group - A recursive mixer group owned by a
Soundscapeaudio scene. - Sound
Group Id - Identifies a sound group within one
Soundscapeinstance. - SoundId
- Identifies a sound within one
Soundscapeinstance. - Soundscape
- The root owner of an application’s audio scene.
- Soundscape
Builder - A validated constructor for a typed
Soundscapescene. - Soundscape
Event - A playback event emitted by one sound in a
Soundscapeinstance. - Spatial
Audio Settings - Scene-wide spatial rendering settings.
- Spatial
Sound - Per-sound spatial rendering settings.
- Waveform
- A multiresolution amplitude overview of an audio track.
- Waveform
Builder - An incrementally decoded waveform suitable for responsive user interfaces.
- Waveform
Decode Summary - A summary of a streaming waveform decode.
- Waveform
Peak - The minimum and maximum sample amplitude in a section of an audio track.
- Waveform
Poll - Result of
WaveformView::poll_visibleandWaveformView::poll_visible_with_budget. - Waveform
Slice - A borrowed, density-limited view into a
Waveform. - Waveform
View - Renderer-agnostic owner of waveform decoding and its visible window.
Enums§
- Distance
Attenuation - Distance-based gain model for a point emitter.
- Hrtf
Error - Errors returned when loading an HRIR bank.
- Output
Error - An error that can occur while opening an audio backend or device.
- Sound
Source - An audio source assignment retained by a
crate::Sound. - Soundscape
Error - The error type for Euphorium operations.
- Spatial
Input - Selects how a sound’s channels are converted to a point emitter.
- Spatial
Renderer - Selects panning or HRTF convolution for spatial sounds.
Traits§
- Sound
Key - Declares the complete set of sounds that a typed
Soundscapescene must contain.
Functions§
- decode_
audio_ to_ waveform_ streaming - Decodes shared audio bytes into finest-resolution peak amplitudes in bounded chunks.
- format_
timestamp - Formats a
Durationas a string in the formatH:MM:SSorM:SS. - format_
timestamp_ secs - Formats f64 seconds as a string in the format
H:MM:SSorM:SS. - parse_
timestamp - Parses a timestamp string in the format
H:MM:SS,M:SS, orSSinto 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.