2020-10-20 18:44:50 +00:00
|
|
|
use crate::{AudioSource, Decodable};
|
2020-12-03 21:57:36 +00:00
|
|
|
use bevy_asset::{Asset, Handle};
|
2020-10-20 18:44:50 +00:00
|
|
|
use parking_lot::RwLock;
|
|
|
|
use std::{collections::VecDeque, fmt};
|
|
|
|
|
2022-01-05 22:30:15 +00:00
|
|
|
/// Use this resource to play audio
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use bevy_ecs::system::Res;
|
|
|
|
/// # use bevy_asset::AssetServer;
|
|
|
|
/// # use bevy_audio::Audio;
|
|
|
|
/// fn play_audio_system(asset_server: Res<AssetServer>, audio: Res<Audio>) {
|
|
|
|
/// audio.play(asset_server.load("my_sound.ogg"));
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub struct Audio<Source = AudioSource>
|
2020-10-20 18:44:50 +00:00
|
|
|
where
|
2022-01-05 22:30:15 +00:00
|
|
|
Source: Asset + Decodable,
|
2020-10-20 18:44:50 +00:00
|
|
|
{
|
2022-01-05 22:30:15 +00:00
|
|
|
/// Queue for playing audio from asset handles
|
|
|
|
pub queue: RwLock<VecDeque<Handle<Source>>>,
|
2020-10-20 18:44:50 +00:00
|
|
|
}
|
|
|
|
|
2022-01-05 22:30:15 +00:00
|
|
|
impl<Source: Asset> fmt::Debug for Audio<Source>
|
2020-10-20 18:44:50 +00:00
|
|
|
where
|
2022-01-05 22:30:15 +00:00
|
|
|
Source: Decodable,
|
2020-10-20 18:44:50 +00:00
|
|
|
{
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
f.debug_struct("Audio").field("queue", &self.queue).finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-05 22:30:15 +00:00
|
|
|
impl<Source> Default for Audio<Source>
|
2020-10-20 18:44:50 +00:00
|
|
|
where
|
2022-01-05 22:30:15 +00:00
|
|
|
Source: Asset + Decodable,
|
2020-10-20 18:44:50 +00:00
|
|
|
{
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
queue: Default::default(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-01-05 22:30:15 +00:00
|
|
|
impl<Source> Audio<Source>
|
2020-10-20 18:44:50 +00:00
|
|
|
where
|
2022-01-05 22:30:15 +00:00
|
|
|
Source: Asset + Decodable,
|
2020-10-20 18:44:50 +00:00
|
|
|
{
|
2022-01-05 22:30:15 +00:00
|
|
|
/// Play audio from a [`Handle`] to the audio source
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use bevy_ecs::system::Res;
|
|
|
|
/// # use bevy_asset::AssetServer;
|
|
|
|
/// # use bevy_audio::Audio;
|
|
|
|
/// fn play_audio_system(asset_server: Res<AssetServer>, audio: Res<Audio>) {
|
|
|
|
/// audio.play(asset_server.load("my_sound.ogg"));
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn play(&self, audio_source: Handle<Source>) {
|
2020-10-20 18:44:50 +00:00
|
|
|
self.queue.write().push_front(audio_source);
|
|
|
|
}
|
|
|
|
}
|