1use alloc::sync::Arc;
2use bevy_asset::{io::Reader, Asset, AssetLoader, LoadContext};
3use bevy_reflect::TypePath;
4use std::io::Cursor;
56/// A source of audio data
7#[derive(impl bevy_asset::VisitAssetDependencies for AudioSource {
fn visit_dependencies(&self,
visit: &mut impl ::core::ops::FnMut(bevy_asset::UntypedAssetId)) {}
}Asset, #[automatically_derived]
impl ::core::fmt::Debug for AudioSource {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "AudioSource",
"bytes", &&self.bytes)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for AudioSource {
#[inline]
fn clone(&self) -> AudioSource {
AudioSource { bytes: ::core::clone::Clone::clone(&self.bytes) }
}
}Clone, const _: () =
{
#[allow(deprecated, reason =
"derives on a deprecated type shouldn't be considered a usage")]
impl bevy_reflect::TypePath for AudioSource where {
fn type_path() -> &'static str {
"bevy_audio::audio_source::AudioSource"
}
fn short_type_path() -> &'static str { "AudioSource" }
fn type_ident() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("AudioSource")
}
fn crate_name() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("bevy_audio::audio_source".split(':').next().unwrap())
}
fn module_path() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("bevy_audio::audio_source")
}
}
};TypePath)]
8pub struct AudioSource {
9/// Raw data of the audio source.
10 ///
11 /// The data must be one of the file formats supported by Bevy (`wav`, `ogg`, `flac`, or `mp3`).
12 /// However, support for these file formats is not part of Bevy's [`default feature set`](https://docs.rs/bevy/latest/bevy/index.html#default-features).
13 /// In order to be able to use these file formats, you will have to enable the appropriate [`optional features`](https://docs.rs/bevy/latest/bevy/index.html#optional-features).
14 ///
15 /// It is decoded using [`rodio::decoder::Decoder`](https://docs.rs/rodio/latest/rodio/decoder/struct.Decoder.html).
16 /// The decoder has conditionally compiled methods
17 /// depending on the features enabled.
18 /// If the format used is not enabled,
19 /// then this will panic with an `UnrecognizedFormat` error.
20pub bytes: Arc<[u8]>,
21}
2223impl AsRef<[u8]> for AudioSource {
24fn as_ref(&self) -> &[u8] {
25&self.bytes
26 }
27}
2829/// Loads files as [`AudioSource`] [`Assets`](bevy_asset::Assets)
30///
31/// This asset loader supports different audio formats based on the enable Bevy features.
32/// The feature `bevy/vorbis` enables loading from `.ogg` files and is enabled by default.
33/// Other file extensions can be loaded from with additional features:
34/// `.mp3` with `bevy/mp3`
35/// `.flac` with `bevy/flac` or `bevy/symphonia-flac`
36/// `.wav` with `bevy/wav` or `bevy/symphonia-wav`
37/// The `bevy/audio-all-formats` feature collection will enable all supported audio formats.
38#[derive(#[automatically_derived]
impl ::core::default::Default for AudioLoader {
#[inline]
fn default() -> AudioLoader { AudioLoader {} }
}Default, const _: () =
{
#[allow(deprecated, reason =
"derives on a deprecated type shouldn't be considered a usage")]
impl bevy_reflect::TypePath for AudioLoader where {
fn type_path() -> &'static str {
"bevy_audio::audio_source::AudioLoader"
}
fn short_type_path() -> &'static str { "AudioLoader" }
fn type_ident() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("AudioLoader")
}
fn crate_name() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("bevy_audio::audio_source".split(':').next().unwrap())
}
fn module_path() -> ::core::option::Option<&'static str> {
::core::option::Option::Some("bevy_audio::audio_source")
}
}
};TypePath)]
39pub struct AudioLoader;
4041impl AssetLoaderfor AudioLoader {
42type Asset = AudioSource;
43type Settings = ();
44type Error = std::io::Error;
4546async fn load(
47&self,
48 reader: &mut dyn Reader,
49 _settings: &Self::Settings,
50 _load_context: &mut LoadContext<'_>,
51 ) -> Result<AudioSource, Self::Error> {
52let mut bytes = Vec::new();
53 reader.read_to_end(&mut bytes).await?;
54Ok(AudioSource {
55 bytes: bytes.into(),
56 })
57 }
5859fn extensions(&self) -> &[&str] {
60&[
61#[cfg(feature = "mp3")]
62"mp3",
63#[cfg(any(feature = "flac", feature = "symphonia-flac"))]
64"flac",
65#[cfg(any(feature = "wav", feature = "symphonia-wav"))]
66"wav",
67#[cfg(any(feature = "vorbis", feature = "symphonia-vorbis"))]
68"oga",
69#[cfg(any(feature = "vorbis", feature = "symphonia-vorbis"))]
70"ogg",
71#[cfg(any(feature = "vorbis", feature = "symphonia-vorbis"))]
72"spx",
73 ]
74 }
75}
7677/// A type implementing this trait can be converted to a [`rodio::Source`] type.
78///
79/// It must be [`Send`] and [`Sync`] in order to be registered.
80/// Types that implement this trait usually contain raw sound data that can be converted into an iterator of samples.
81/// This trait is implemented for [`AudioSource`].
82/// Check the example [`decodable`](https://github.com/bevyengine/bevy/blob/latest/examples/audio/decodable.rs) for how to implement this trait on a custom type.
83pub trait Decodable: Send + Sync + 'static {
84/// The type of the iterator of the audio samples,
85 /// which iterates over samples of type [`rodio::Sample`].
86 /// Must be a [`rodio::Source`] so that it can provide information on the audio it is iterating over.
87type Decoder: rodio::Source + Send + Iterator<Item = rodio::Sample>;
8889/// Build and return a [`Self::Decoder`] of the implementing type
90fn decoder(&self) -> Self::Decoder;
91}
9293impl Decodablefor AudioSource {
94type Decoder = rodio::Decoder<Cursor<AudioSource>>;
9596fn decoder(&self) -> Self::Decoder {
97 rodio::Decoder::new(Cursor::new(self.clone())).unwrap()
98 }
99}
100101/// A trait that allows adding a custom audio source to the object.
102/// This is implemented for [`App`][bevy_app::App] to allow registering custom [`Decodable`] types.
103pub trait AddAudioSource {
104/// Registers an audio source.
105 /// The type must implement [`Decodable`],
106 /// so that it can be converted to a [`rodio::Source`] type,
107 /// and [`Asset`], so that it can be registered as an asset.
108 /// To use this method on [`App`][bevy_app::App],
109 /// the [audio][super::AudioPlugin] and [asset][bevy_asset::AssetPlugin] plugins must be added first.
110fn add_audio_source<T>(&mut self) -> &mut Self
111where
112T: Decodable + Asset,
113f32: rodio::cpal::FromSample<rodio::Sample>;
114}