From ac04c71d97ad22435b69acc20d5f64aa568bb1b9 Mon Sep 17 00:00:00 2001 From: forbjok Date: Tue, 8 Jun 2021 03:14:38 +0000 Subject: [PATCH] Fix Bevy crashing if no audio device is found (#2269) Fixes https://github.com/bevyengine/bevy/issues/850 --- crates/bevy_audio/src/audio_output.rs | 32 ++++++++++++++++++--------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/crates/bevy_audio/src/audio_output.rs b/crates/bevy_audio/src/audio_output.rs index 075195c50b..9d3fb48115 100644 --- a/crates/bevy_audio/src/audio_output.rs +++ b/crates/bevy_audio/src/audio_output.rs @@ -1,6 +1,7 @@ use crate::{Audio, AudioSource, Decodable}; use bevy_asset::{Asset, Assets}; use bevy_ecs::world::World; +use bevy_utils::tracing::warn; use rodio::{OutputStream, OutputStreamHandle, Sink}; use std::marker::PhantomData; @@ -9,8 +10,8 @@ pub struct AudioOutput

where P: Decodable, { - _stream: OutputStream, - stream_handle: OutputStreamHandle, + _stream: Option, + stream_handle: Option, phantom: PhantomData

, } @@ -19,12 +20,19 @@ where P: Decodable, { fn default() -> Self { - let (stream, stream_handle) = OutputStream::try_default().unwrap(); - - Self { - _stream: stream, - stream_handle, - phantom: PhantomData, + if let Ok((stream, stream_handle)) = OutputStream::try_default() { + 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, + } } } } @@ -36,9 +44,11 @@ where <

::Decoder as Iterator>::Item: rodio::Sample + Send + Sync, { fn play_source(&self, audio_source: &P) { - let sink = Sink::try_new(&self.stream_handle).unwrap(); - sink.append(audio_source.decoder()); - sink.detach(); + if let Some(stream_handle) = &self.stream_handle { + let sink = Sink::try_new(&stream_handle).unwrap(); + sink.append(audio_source.decoder()); + sink.detach(); + } } fn try_play_queued(&self, audio_sources: &Assets

, audio: &mut Audio

) {