diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index f42db09df654c..31ee5f503adc3 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -1,17 +1,28 @@ use crate::{Audio, AudioSource, Decodable}; use bevy_asset::{Asset, Assets}; -use bevy_ecs::system::{NonSend, Res, ResMut}; +use bevy_ecs::system::{Res, ResMut, Resource}; use bevy_reflect::TypeUuid; use bevy_utils::tracing::warn; use rodio::{OutputStream, OutputStreamHandle, Sink, Source}; use std::marker::PhantomData; /// Used internally to play audio on the current "audio device" +/// +/// ## Note +/// +/// Initializing this resource will leak [`rodio::OutputStream`](rodio::OutputStream) +/// using [`std::mem::forget`]. +/// This is done to avoid storing this in the struct (and making this `!Send`) +/// while preventing it from dropping (to avoid halting of audio). +/// +/// This is fine when initializing this once (as is default when adding this plugin), +/// since the memory cost will be the same. +/// However, repeatedly inserting this resource into the app will **leak more memory**. +#[derive(Resource)] pub struct AudioOutput where Source: Decodable, { - _stream: Option, stream_handle: Option, phantom: PhantomData, } @@ -22,15 +33,15 @@ where { fn default() -> Self { if let Ok((stream, stream_handle)) = OutputStream::try_default() { + // We leak `OutputStream` to prevent the audio from stopping. + std::mem::forget(stream); Self { - _stream: Some(stream), stream_handle: Some(stream_handle), phantom: PhantomData, } } else { warn!("No audio device found."); Self { - _stream: None, stream_handle: None, phantom: PhantomData, } @@ -84,7 +95,7 @@ where /// Plays audio currently queued in the [`Audio`] resource through the [`AudioOutput`] resource pub fn play_queued_audio_system( - audio_output: NonSend>, + audio_output: Res>, audio_sources: Option>>, mut audio: ResMut>, mut sinks: ResMut>, diff --git a/crates/bevy_audio/src/lib.rs b/crates/bevy_audio/src/lib.rs index 7c4db0090c77c..9fc4a5484b88c 100644 --- a/crates/bevy_audio/src/lib.rs +++ b/crates/bevy_audio/src/lib.rs @@ -50,7 +50,7 @@ pub struct AudioPlugin; impl Plugin for AudioPlugin { fn build(&self, app: &mut App) { - app.init_non_send_resource::>() + app.init_resource::>() .add_asset::() .add_asset::() .init_resource::>()