Skip to content

Commit

Permalink
handle error during audio stream creation
Browse files Browse the repository at this point in the history
  • Loading branch information
agourlay committed Sep 21, 2024
1 parent 3ec0f03 commit 5f61a71
Showing 1 changed file with 31 additions and 6 deletions.
37 changes: 31 additions & 6 deletions src/audio/midi_player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::audio::midi_sequencer::MidiSequencer;
use crate::audio::FIRST_TICK;
use crate::parser::song_parser::Song;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::DefaultStreamConfigError;
use rustysynth::{SoundFont, Synthesizer, SynthesizerSettings};
use std::fs::File;
use std::path::PathBuf;
Expand Down Expand Up @@ -148,14 +149,26 @@ impl AudioPlayer {
}
} else {
self.is_playing = true;

// Initialize audio output stream
let stream = new_output_stream(
self.sequencer.clone(),
self.player_params.clone(),
self.synthesizer.clone(),
self.sound_font.clone(),
self.beat_sender.clone(),
);
self.stream = Some(Rc::new(stream));

match stream {
Ok(stream) => {
self.stream = Some(Rc::new(stream));
}
Err(err) => {
log::error!("Failed to create audio stream: {}", err);
self.is_playing = false;
self.stream = None;
}
}
}
}

Expand All @@ -181,19 +194,31 @@ impl AudioPlayer {
}
}

#[derive(Debug, thiserror::Error)]
enum AudioStreamError {
#[error("audio device not found")]
CpalDeviceNotFount,
#[error("no output configuration found: {0}")]
CpalOutputConfigNotFound(DefaultStreamConfigError),
}

/// Create a new output stream for audio playback.
fn new_output_stream(
sequencer: Arc<Mutex<MidiSequencer>>,
player_params: Arc<Mutex<MidiPlayerParams>>,
synthesizer: Arc<Mutex<Synthesizer>>,
sound_font: Arc<SoundFont>,
beat_notifier: Arc<Sender<usize>>,
) -> cpal::Stream {
// Initialize audio output
) -> Result<cpal::Stream, AudioStreamError> {
let host = cpal::default_host();
let device = host.default_output_device().unwrap();
let Some(device) = host.default_output_device() else {
return Err(AudioStreamError::CpalDeviceNotFount);
};

let config = device
.default_output_config()
.map_err(AudioStreamError::CpalOutputConfigNotFound)?;

let config = device.default_output_config().unwrap();
assert!(
config.sample_format().is_float(),
"{}",
Expand Down Expand Up @@ -344,5 +369,5 @@ fn new_output_stream(
);
let stream = stream.unwrap();
stream.play().unwrap();
stream
Ok(stream)
}

0 comments on commit 5f61a71

Please sign in to comment.