khora_data/ecs/components/audio/source.rs
1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Defines the `AudioSource` component for emitting sound.
16
17use crate::assets::SoundData;
18use khora_core::asset::AssetHandle;
19use khora_macros::Component;
20
21/// The internal playback state of an active sound.
22/// This will be managed by the `AudioMixingLane`.
23#[derive(Debug, Clone, PartialEq)]
24pub struct PlaybackState {
25 /// The current position in the sample data, in samples.
26 pub cursor: f32,
27}
28
29/// An ECS component that makes an entity an emitter of sound.
30#[derive(Debug, Clone, Component)]
31pub struct AudioSource {
32 /// A handle to the sound data to be played.
33 pub handle: AssetHandle<SoundData>,
34 /// The volume of the sound, where 1.0 is normal volume.
35 pub volume: f32,
36 /// Whether the sound should loop back to the beginning when it finishes.
37 pub looping: bool,
38 /// Whether the sound should start playing automatically when this component is added.
39 pub autoplay: bool,
40 /// The internal playback state. This should be treated as read-only
41 /// by most systems outside of the audio engine itself.
42 pub state: Option<PlaybackState>,
43}
44
45impl AudioSource {
46 /// Creates a new `AudioSource`.
47 pub fn new(handle: AssetHandle<SoundData>) -> Self {
48 Self {
49 handle,
50 volume: 1.0,
51 looping: false,
52 autoplay: true,
53 state: None,
54 }
55 }
56}