SoundSource

Struct SoundSource 

Source
pub struct SoundSource { /* private fields */ }
Expand description

See module info.

Implementations§

Source§

impl SoundSource

Source

pub const NAME: &'static str = "name"

Source

pub const PANNING: &'static str = "panning"

Source

pub const PITCH: &'static str = "pitch"

Source

pub const GAIN: &'static str = "gain"

Source

pub const LOOPING: &'static str = "looping"

Source

pub const SPATIAL_BLEND: &'static str = "spatial_blend"

Source

pub const RESAMPLING_MULTIPLIER: &'static str = "resampling_multiplier"

Source

pub const STATUS: &'static str = "status"

Source

pub const BUS: &'static str = "bus"

Source

pub const PLAY_ONCE: &'static str = "play_once"

Source

pub const RADIUS: &'static str = "radius"

Source

pub const POSITION: &'static str = "position"

Source

pub const MAX_DISTANCE: &'static str = "max_distance"

Source

pub const ROLLOFF_FACTOR: &'static str = "rolloff_factor"

Source§

impl SoundSource

Source

pub fn set_name<N: AsRef<str>>(&mut self, name: N)

Sets new name of the sound source.

Source

pub fn name(&self) -> &str

Returns the name of the sound source.

Source

pub fn name_owned(&self) -> String

Returns the name of the sound source.

Source

pub fn set_spatial_blend(&mut self, k: f32)

Sets spatial blend factor. It defines how much the source will be 2D and 3D sound at the same time. Set it to 0.0 to make the sound fully 2D and 1.0 to make it fully 3D. Middle values will make sound proportionally 2D and 3D at the same time.

Source

pub fn spatial_blend(&self) -> f32

Returns spatial blend factor.

Source

pub fn set_buffer( &mut self, buffer: Option<SoundBufferResource>, ) -> Result<Option<SoundBufferResource>, SoundError>

Changes buffer of source. Returns old buffer. Source will continue playing from beginning, old position will be discarded.

Source

pub fn buffer(&self) -> Option<SoundBufferResource>

Returns current buffer if any.

Source

pub fn set_play_once(&mut self, play_once: bool)

Marks buffer for single play. It will be automatically destroyed when it will finish playing.

§Notes

Make sure you not using handles to “play once” sounds, attempt to get reference of “play once” sound may result in panic if source already deleted. Looping sources will never be automatically deleted because their playback never stops.

Source

pub fn is_play_once(&self) -> bool

Returns true if this source is marked for single play, false - otherwise.

Source

pub fn set_gain(&mut self, gain: f32) -> &mut Self

Sets new gain (volume) of sound. Value should be in 0..1 range, but it is not clamped and larger values can be used to “overdrive” sound.

§Notes

Physical volume has non-linear scale (logarithmic) so perception of sound at 0.25 gain will be different if logarithmic scale was used.

Source

pub fn gain(&self) -> f32

Returns current gain (volume) of sound. Value is in 0..1 range.

Source

pub fn set_panning(&mut self, panning: f32) -> &mut Self

Sets panning coefficient. Value must be in -1..+1 range. Where -1 - only left channel will be audible, 0 - both, +1 - only right.

Source

pub fn panning(&self) -> f32

Returns current panning coefficient in -1..+1 range. For more info see set_panning. Default value is 0.

Source

pub fn status(&self) -> Status

Returns status of sound source.

Source

pub fn play(&mut self) -> &mut Self

Changes status to Playing.

Source

pub fn pause(&mut self) -> &mut Self

Changes status to Paused

Source

pub fn set_looping(&mut self, looping: bool) -> &mut Self

Enabled or disables sound looping. Looping sound will never stop by itself, but can be stopped or paused by calling stop or pause methods. Useful for music, ambient sounds, etc.

Source

pub fn is_looping(&self) -> bool

Returns looping status.

Source

pub fn set_pitch(&mut self, pitch: f64) -> &mut Self

Sets sound pitch. Defines “tone” of sounds. Default value is 1.0

Source

pub fn pitch(&self) -> f64

Returns pitch of sound source.

Source

pub fn stop(&mut self) -> Result<(), SoundError>

Stops sound source. Automatically rewinds streaming buffers.

Source

pub fn set_position(&mut self, position: Vector3<f32>) -> &mut Self

Sets position of source in world space.

Examples found in repository?
examples/play_spatial_sound.rs (lines 76-80)
37fn main() {
38    // Initialize sound engine with default output device.
39    let engine = SoundEngine::new().unwrap();
40
41    // Initialize new sound context.
42    let context = SoundContext::new();
43
44    engine.state().add_context(context.clone());
45
46    // Load sound buffer.
47    let drop_buffer = SoundBufferResource::new_generic(
48        block_on(DataSource::from_file(
49            "examples/data/drop.wav",
50            // Load from the default resource io (File system)
51            &FsResourceIo,
52        ))
53        .unwrap(),
54    )
55    .unwrap();
56
57    // Create spatial source - spatial sources can be positioned in space.
58    let source = SoundSourceBuilder::new()
59        .with_buffer(drop_buffer)
60        .with_looping(true)
61        .with_status(Status::Playing)
62        .build()
63        .unwrap();
64
65    // Each sound sound must be added to context, context takes ownership on source
66    // and returns pool handle to it by which it can be accessed later on if needed.
67    let source_handle: Handle<SoundSource> = context.state().add_source(source);
68
69    // Move sound around listener for some time.
70    let start_time = time::Instant::now();
71    let mut angle = 0.0f32;
72    while (time::Instant::now() - start_time).as_secs() < 11 {
73        let axis = Vector3::y_axis();
74        let rotation_matrix =
75            UnitQuaternion::from_axis_angle(&axis, angle.to_radians()).to_homogeneous();
76        context.state().source_mut(source_handle).set_position(
77            rotation_matrix
78                .transform_point(&Point3::new(0.0, 0.0, 3.0))
79                .coords,
80        );
81
82        angle += 3.6;
83
84        // Limit rate of updates.
85        thread::sleep(Duration::from_millis(100));
86    }
87}
More examples
Hide additional examples
examples/hrtf.rs (lines 102-106)
41fn main() {
42    // Initialize sound engine with default output device.
43    let engine = SoundEngine::new().unwrap();
44
45    let hrir_path = PathBuf::from("examples/data/IRC_1002_C.bin");
46    let hrir_sphere = HrirSphere::from_file(&hrir_path, context::SAMPLE_RATE).unwrap();
47
48    // Initialize new sound context with default output device.
49    let context = SoundContext::new();
50
51    engine.state().add_context(context.clone());
52
53    // Set HRTF renderer instead of default.
54    context
55        .state()
56        .set_renderer(Renderer::HrtfRenderer(HrtfRenderer::new(
57            HrirSphereResource::from_hrir_sphere(hrir_sphere, hrir_path.into()),
58        )));
59
60    // Create some sounds.
61    let sound_buffer = SoundBufferResource::new_generic(
62        block_on(DataSource::from_file(
63            "examples/data/door_open.wav", // Load from the default resource io (File system)
64            &FsResourceIo,
65        ))
66        .unwrap(),
67    )
68    .unwrap();
69    let source = SoundSourceBuilder::new()
70        .with_buffer(sound_buffer)
71        .with_status(Status::Playing)
72        .build()
73        .unwrap();
74    context.state().add_source(source);
75
76    let sound_buffer = SoundBufferResource::new_generic(
77        block_on(DataSource::from_file(
78            "examples/data/helicopter.wav", // Load from the default resource io (File system)
79            &FsResourceIo,
80        ))
81        .unwrap(),
82    )
83    .unwrap();
84    let source = SoundSourceBuilder::new()
85        .with_buffer(sound_buffer)
86        .with_status(Status::Playing)
87        .with_looping(true)
88        .build()
89        .unwrap();
90    let source_handle = context.state().add_source(source);
91
92    // Move source sound around listener for some time.
93    let start_time = time::Instant::now();
94    let mut angle = 0.0f32;
95    while (time::Instant::now() - start_time).as_secs() < 360 {
96        // Separate scope for update to make sure that mutex lock will be released before
97        // thread::sleep will be called so context can actually work in background thread.
98        {
99            let axis = Vector3::y_axis();
100            let rotation_matrix =
101                UnitQuaternion::from_axis_angle(&axis, angle.to_radians()).to_homogeneous();
102            context.state().source_mut(source_handle).set_position(
103                rotation_matrix
104                    .transform_point(&Point3::new(0.0, 0.0, 3.0))
105                    .coords,
106            );
107
108            angle += 1.6;
109
110            println!(
111                "Sound render time {:?}",
112                context.state().full_render_duration()
113            );
114        }
115
116        // Limit rate of updates.
117        thread::sleep(Duration::from_millis(100));
118    }
119}
examples/reverb.rs (lines 115-119)
41fn main() {
42    let hrir_path = PathBuf::from("examples/data/IRC_1002_C.bin");
43    let hrir_sphere = HrirSphere::from_file(&hrir_path, context::SAMPLE_RATE).unwrap();
44
45    // Initialize sound engine with default output device.
46    let engine = SoundEngine::new().unwrap();
47
48    // Initialize new sound context.
49    let context = SoundContext::new();
50
51    engine.state().add_context(context.clone());
52
53    // Set HRTF renderer instead of default for binaural sound.
54    context
55        .state()
56        .set_renderer(Renderer::HrtfRenderer(HrtfRenderer::new(
57            HrirSphereResource::from_hrir_sphere(hrir_sphere, hrir_path.into()),
58        )));
59
60    {
61        // Create reverb effect and set its decay time.
62        let mut reverb = Reverb::new();
63        reverb.set_decay_time(10.0);
64
65        // Add the reverb to the primary bus.
66        let mut state = context.state();
67        state
68            .bus_graph_mut()
69            .primary_bus_mut()
70            .add_effect(Effect::Reverb(reverb));
71    }
72
73    // Create some sounds.
74    let sound_buffer = SoundBufferResource::new_generic(
75        block_on(DataSource::from_file(
76            "examples/data/door_open.wav", // Load from the default resource io (File system)
77            &FsResourceIo,
78        ))
79        .unwrap(),
80    )
81    .unwrap();
82    let source = SoundSourceBuilder::new()
83        // Each sound must specify the bus to which it will output the samples. By default it is "Primary" bus.
84        .with_bus("Primary")
85        .with_buffer(sound_buffer)
86        .with_status(Status::Playing)
87        .build()
88        .unwrap();
89    context.state().add_source(source);
90
91    let sound_buffer = SoundBufferResource::new_generic(
92        block_on(DataSource::from_file(
93            "examples/data/drop.wav",
94            // Load from the default resource io (File system)
95            &FsResourceIo,
96        ))
97        .unwrap(),
98    )
99    .unwrap();
100    let source = SoundSourceBuilder::new()
101        .with_buffer(sound_buffer)
102        .with_status(Status::Playing)
103        .with_looping(true)
104        .build()
105        .unwrap();
106    let drop_sound_handle = context.state().add_source(source);
107
108    // Move sound around listener for some time.
109    let start_time = time::Instant::now();
110    let mut angle = 0.0f32;
111    while (time::Instant::now() - start_time).as_secs() < 360 {
112        let axis = Vector3::y_axis();
113        let rotation_matrix =
114            UnitQuaternion::from_axis_angle(&axis, angle.to_radians()).to_homogeneous();
115        context.state().source_mut(drop_sound_handle).set_position(
116            rotation_matrix
117                .transform_point(&Point3::new(0.0, 0.0, 1.0))
118                .coords,
119        );
120
121        angle += 1.6;
122
123        println!(
124            "Sound render time {:?}",
125            context.state().full_render_duration()
126        );
127
128        // Limit rate of context updates.
129        thread::sleep(Duration::from_millis(100));
130    }
131}
Source

pub fn position(&self) -> Vector3<f32>

Returns positions of source.

Source

pub fn set_radius(&mut self, radius: f32) -> &mut Self

Sets radius of imaginable sphere around source in which no distance attenuation is applied.

Source

pub fn radius(&self) -> f32

Returns radius of source.

Source

pub fn set_rolloff_factor(&mut self, rolloff_factor: f32) -> &mut Self

Sets rolloff factor. Rolloff factor is used in distance attenuation and has different meaning in various distance models. It is applicable only for InverseDistance and ExponentDistance distance models. See DistanceModel docs for formulae.

Source

pub fn rolloff_factor(&self) -> f32

Returns rolloff factor.

Source

pub fn set_max_distance(&mut self, max_distance: f32) -> &mut Self

Sets maximum distance until which distance gain will be applicable. Basically it doing this min(max(distance, radius), max_distance) which clamps distance in radius..max_distance range. From listener’s perspective this will sound like source has stopped decreasing its volume even if distance continue to grow.

Source

pub fn max_distance(&self) -> f32

Returns max distance.

Source

pub fn set_bus<S: AsRef<str>>(&mut self, bus: S)

Sets new name of the target audio bus. The name must be valid, otherwise the sound won’t play! Default is AudioBusGraph::PRIMARY_BUS.

Source

pub fn bus(&self) -> &str

Return the name of the target audio bus.

Source

pub fn playback_time(&self) -> Duration

Returns playback duration.

Source

pub fn set_playback_time(&mut self, time: Duration)

Sets playback duration.

Trait Implementations§

Source§

impl Clone for SoundSource

Source§

fn clone(&self) -> SoundSource

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for SoundSource

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for SoundSource

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for SoundSource

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl Reflect for SoundSource

Source§

fn source_path() -> &'static str

Source§

fn type_name(&self) -> &'static str

Source§

fn doc(&self) -> &'static str

Source§

fn assembly_name(&self) -> &'static str

Returns a parent assembly name of the type that implements this trait. WARNING: You should use proc-macro (#[derive(Reflect)]) to ensure that this method will return correct assembly name. In other words - there’s no guarantee, that any implementation other than proc-macro will return a correct name of the assembly. Alternatively, you can use env!("CARGO_PKG_NAME") as an implementation.
Source§

fn type_assembly_name() -> &'static str

Returns a parent assembly name of the type that implements this trait. WARNING: You should use proc-macro (#[derive(Reflect)]) to ensure that this method will return correct assembly name. In other words - there’s no guarantee, that any implementation other than proc-macro will return a correct name of the assembly. Alternatively, you can use env!("CARGO_PKG_NAME") as an implementation.
Source§

fn fields_info(&self, func: &mut dyn FnMut(&[FieldInfo<'_, '_>]))

Source§

fn into_any(self: Box<Self>) -> Box<dyn Any>

Source§

fn set( &mut self, value: Box<dyn Reflect>, ) -> Result<Box<dyn Reflect>, Box<dyn Reflect>>

Source§

fn as_any(&self, func: &mut dyn FnMut(&dyn Any))

Source§

fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any))

Source§

fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect))

Source§

fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect))

Source§

fn fields(&self, func: &mut dyn FnMut(&[&dyn Reflect]))

Source§

fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [&mut dyn Reflect]))

Source§

fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>))

Source§

fn field_mut( &mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>), )

Source§

fn set_field( &mut self, field: &str, value: Box<dyn Reflect>, func: &mut dyn FnMut(Result<Box<dyn Reflect>, Box<dyn Reflect>>), )

Calls user method specified with #[reflect(setter = ..)] or falls back to Reflect::field_mut
Source§

fn as_array(&self, func: &mut dyn FnMut(Option<&(dyn ReflectArray + 'static)>))

Source§

fn as_array_mut( &mut self, func: &mut dyn FnMut(Option<&mut (dyn ReflectArray + 'static)>), )

Source§

fn as_list(&self, func: &mut dyn FnMut(Option<&(dyn ReflectList + 'static)>))

Source§

fn as_list_mut( &mut self, func: &mut dyn FnMut(Option<&mut (dyn ReflectList + 'static)>), )

Source§

fn as_inheritable_variable( &self, func: &mut dyn FnMut(Option<&(dyn ReflectInheritableVariable + 'static)>), )

Source§

fn as_inheritable_variable_mut( &mut self, func: &mut dyn FnMut(Option<&mut (dyn ReflectInheritableVariable + 'static)>), )

Source§

fn as_hash_map( &self, func: &mut dyn FnMut(Option<&(dyn ReflectHashMap + 'static)>), )

Source§

fn as_hash_map_mut( &mut self, func: &mut dyn FnMut(Option<&mut (dyn ReflectHashMap + 'static)>), )

Source§

impl Visit for SoundSource

Source§

fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult

Read or write this value, depending on whether Visitor::is_reading() is true or false. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsyncTaskResult for T
where T: Any + Send + 'static,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts self reference as a reference to Any. Could be used to downcast a trait object to a particular type.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts self reference as a reference to Any. Could be used to downcast a trait object to a particular type.
Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Source§

impl<T> FieldValue for T
where T: 'static,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Casts self to a &dyn Any
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<R> GetField for R
where R: Reflect,

Source§

fn get_field<T>(&self, name: &str, func: &mut dyn FnMut(Option<&T>))
where T: 'static,

Source§

fn get_field_mut<T>(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut T>))
where T: 'static,

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ReflectBase for T
where T: Reflect,

Source§

fn as_any_raw(&self) -> &(dyn Any + 'static)

Source§

fn as_any_raw_mut(&mut self) -> &mut (dyn Any + 'static)

Source§

impl<T> ResolvePath for T
where T: Reflect,

Source§

fn resolve_path<'p>( &self, path: &'p str, func: &mut dyn FnMut(Result<&(dyn Reflect + 'static), ReflectPathError<'p>>), )

Source§

fn resolve_path_mut<'p>( &mut self, path: &'p str, func: &mut dyn FnMut(Result<&mut (dyn Reflect + 'static), ReflectPathError<'p>>), )

Source§

fn get_resolve_path<'p, T>( &self, path: &'p str, func: &mut dyn FnMut(Result<&T, ReflectPathError<'p>>), )
where T: Reflect,

Source§

fn get_resolve_path_mut<'p, T>( &mut self, path: &'p str, func: &mut dyn FnMut(Result<&mut T, ReflectPathError<'p>>), )
where T: Reflect,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

Source§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
Source§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
Source§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
Source§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V