nightshade-api 0.41.0

Procedural high level API for the nightshade game engine
Documentation
//! Sound loading and one call playback. The listener rides the active camera.

use nightshade::prelude::*;

/// Registers a sound under `name` from ogg, wav, mp3, or flac bytes.
pub fn load_sound(world: &mut World, name: &str, bytes: &[u8]) {
    match nightshade::ecs::audio::systems::load_sound_from_cursor(bytes.to_vec()) {
        Ok(data) => audio_engine_load_sound(&mut world.resources.audio, name, data),
        Err(error) => tracing::error!("Failed to load sound {name}: {error}"),
    }
}

/// Plays a loaded sound once, everywhere. Returns the source entity, which
/// you can [`despawn`](crate::prelude::despawn) to stop it early.
pub fn play_sound(world: &mut World, name: &str) -> Entity {
    let entity = spawn_entities(world, AUDIO_SOURCE, 1)[0];
    world
        .core
        .set_audio_source(entity, AudioSource::new(name).playing());
    entity
}

/// Plays a loaded sound on repeat until despawned. The call for music and
/// ambience.
pub fn play_sound_looping(world: &mut World, name: &str) -> Entity {
    let entity = spawn_entities(world, AUDIO_SOURCE, 1)[0];
    world
        .core
        .set_audio_source(entity, AudioSource::new(name).with_looping(true).playing());
    entity
}

/// Sets the volume of a playing sound, 0.0 silent to 1.0 full.
pub fn set_volume(world: &mut World, entity: Entity, volume: f32) {
    if let Some(source) = world.core.get_audio_source_mut(entity) {
        source.volume = volume;
    }
}

/// Plays a loaded sound once at a position in the world, spatialized
/// relative to the camera.
pub fn play_sound_at(world: &mut World, name: &str, position: Vec3) -> Entity {
    let entity = spawn_entities(
        world,
        AUDIO_SOURCE | LOCAL_TRANSFORM | LOCAL_TRANSFORM_DIRTY | GLOBAL_TRANSFORM,
        1,
    )[0];
    assign_local_transform(
        world,
        entity,
        LocalTransform {
            translation: position,
            ..Default::default()
        },
    );
    world
        .core
        .set_audio_source(entity, AudioSource::new(name).with_spatial(true).playing());
    entity
}