1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
//! `kira` integration for `assets_manager`
//!
//! This crate provides wrappers around `kira` sounds types that implement
//! `assets_manager` traits.

#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
#![forbid(unsafe_code)]

const AVAILABLE_EXTENSIONS: &[&str] = &[
    #[cfg(feature = "ogg")]
    "ogg",
    #[cfg(feature = "mp3")]
    "mp3",
    #[cfg(feature = "flac")]
    "flac",
    #[cfg(feature = "wav")]
    "wav",
];

pub use static_sound::StaticSound;
pub use streaming::StreamingSound;

mod static_sound {
    use assets_manager::{loader, Asset};
    use kira::sound::static_sound::{StaticSoundData, StaticSoundSettings};
    use std::io::Cursor;

    /// A wrapper around [`StaticSoundData`] that implements [`Asset`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use kira::manager::{backend::DefaultBackend, AudioManager, AudioManagerSettings};
    /// use assets_manager_kira::StaticSound;
    ///
    /// let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
    /// let cache = assets_manager::AssetCache::new("assets")?;
    ///
    /// loop {
    ///     let sound_data = cache.load::<StaticSound>("example.audio.beep")?;
    ///     manager.play(sound_data.cloned())?;
    ///     std::thread::sleep(std::time::Duration::from_secs(1));
    /// }
    ///
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    #[derive(Clone)]
    #[repr(transparent)]
    pub struct StaticSound(pub StaticSoundData);

    impl StaticSound {
        /// Returns the duration of the audio.
        pub fn duration(&self) -> std::time::Duration {
            self.0.duration()
        }

        /// Returns a clone of the `StaticSound` with the specified settings.
        pub fn with_settings(&self, settings: StaticSoundSettings) -> Self {
            Self(self.0.with_settings(settings))
        }
    }

    impl loader::Loader<StaticSound> for loader::SoundLoader {
        fn load(
            content: std::borrow::Cow<[u8]>,
            _: &str,
        ) -> Result<StaticSound, assets_manager::BoxedError> {
            let sound = StaticSoundData::from_cursor(Cursor::new(content.into_owned()))?;
            Ok(StaticSound(sound))
        }
    }

    impl Asset for StaticSound {
        const EXTENSIONS: &'static [&'static str] = crate::AVAILABLE_EXTENSIONS;
        type Loader = loader::SoundLoader;
    }

    impl kira::sound::SoundData for StaticSound {
        type Error = <StaticSoundData as kira::sound::SoundData>::Error;
        type Handle = <StaticSoundData as kira::sound::SoundData>::Handle;

        #[inline]
        fn into_sound(self) -> Result<(Box<dyn kira::sound::Sound>, Self::Handle), Self::Error> {
            self.0.into_sound()
        }
    }

    impl From<StaticSound> for StaticSoundData {
        #[inline]
        fn from(sound: StaticSound) -> Self {
            sound.0
        }
    }

    impl std::fmt::Debug for StaticSound {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            self.0.fmt(f)
        }
    }
}

#[cfg(not(target_arch = "wasm32"))]
#[cfg_attr(docsrs, doc(cfg(not(target_arch = "wasm32"))))]
mod streaming {
    use assets_manager::{loader, Asset};
    use kira::sound::{
        streaming::{StreamingSoundData, StreamingSoundSettings},
        FromFileError,
    };
    use std::io::Cursor;

    /// A wrapper around [`StreamingSoundData`] that implements [`Asset`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use kira::manager::{backend::DefaultBackend, AudioManager, AudioManagerSettings};
    /// use assets_manager_kira::StreamingSound;
    ///
    /// let mut manager = AudioManager::<DefaultBackend>::new(AudioManagerSettings::default())?;
    /// let cache = assets_manager::AssetCache::new("assets")?;
    ///
    /// loop {
    ///     let sound_data = cache.load::<StreamingSound>("example.audio.beep")?;
    ///     manager.play(sound_data.cloned())?;
    ///     std::thread::sleep(std::time::Duration::from_secs(1));
    /// }
    ///
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    #[derive(Clone)]
    pub struct StreamingSound {
        /// Settings for the sound.
        pub settings: StreamingSoundSettings,
        bytes: assets_manager::SharedBytes,
    }

    impl StreamingSound {
        /// Returns a clone of the `StreamingSound` with the specified settings.
        pub fn with_settings(&self, settings: StreamingSoundSettings) -> Self {
            Self {
                settings,
                bytes: self.bytes.clone(),
            }
        }

        fn try_into_kira(self) -> Result<StreamingSoundData<FromFileError>, FromFileError> {
            let mut sound = StreamingSoundData::from_cursor(Cursor::new(self.bytes))?;
            sound.settings = self.settings;
            Ok(sound)
        }
    }

    impl loader::Loader<StreamingSound> for loader::SoundLoader {
        fn load(
            content: std::borrow::Cow<[u8]>,
            _: &str,
        ) -> Result<StreamingSound, assets_manager::BoxedError> {
            let bytes = assets_manager::SharedBytes::from(content);
            let settings = StreamingSoundSettings::default();

            // Check that the audio file is valid.
            let _ = StreamingSoundData::from_cursor(Cursor::new(bytes.clone()))?;

            Ok(StreamingSound { settings, bytes })
        }
    }

    impl Asset for StreamingSound {
        const EXTENSIONS: &'static [&'static str] = crate::AVAILABLE_EXTENSIONS;
        type Loader = loader::SoundLoader;
    }

    impl kira::sound::SoundData for StreamingSound {
        type Error = <StreamingSoundData<FromFileError> as kira::sound::SoundData>::Error;
        type Handle = <StreamingSoundData<FromFileError> as kira::sound::SoundData>::Handle;

        #[inline]
        fn into_sound(self) -> Result<(Box<dyn kira::sound::Sound>, Self::Handle), Self::Error> {
            self.try_into_kira()?.into_sound()
        }
    }

    impl From<StreamingSound> for StreamingSoundData<FromFileError> {
        fn from(sound: StreamingSound) -> Self {
            sound.try_into_kira().expect("reading succeded earlier")
        }
    }

    impl std::fmt::Debug for StreamingSound {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("StreamingSound")
                .field("settings", &self.settings)
                .finish_non_exhaustive()
        }
    }
}