1use rodio::Source;
2
3use crate::ecs::plugin::Plugin;
4
5#[derive(Debug)]
6pub enum AudioError {
7 Io(std::io::Error),
8 Decode(String),
9 Device(String),
10}
11
12impl std::fmt::Display for AudioError {
13 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
14 match self {
15 Self::Io(e) => write!(f, "failed to read sound file: {e}"),
16 Self::Decode(msg) => write!(f, "failed to decode audio: {msg}"),
17 Self::Device(msg) => write!(f, "audio output device error: {msg}"),
18 }
19 }
20}
21
22impl std::error::Error for AudioError {
23 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
24 match self {
25 Self::Io(e) => Some(e),
26 _ => None,
27 }
28 }
29}
30
31impl From<std::io::Error> for AudioError {
32 fn from(e: std::io::Error) -> Self {
33 Self::Io(e)
34 }
35}
36
37#[derive(Clone)]
38pub struct Sound(rodio::buffer::SamplesBuffer);
39
40pub struct SoundBuilder;
41
42impl SoundBuilder {
43 pub fn from_file(path: &str) -> Result<Sound, AudioError> {
44 let file = std::fs::File::open(path)?;
45 let decoder = rodio::Decoder::new(std::io::BufReader::new(file))
46 .map_err(|e| AudioError::Decode(e.to_string()))?;
47 let channels = decoder.channels();
48 let sample_rate = decoder.sample_rate();
49 let samples: Vec<f32> = decoder.collect();
50 Ok(Sound(rodio::buffer::SamplesBuffer::new(channels, sample_rate, samples)))
51 }
52}
53
54pub struct PlayingSound(rodio::Player);
55
56impl PlayingSound {
57 pub fn set_volume(&self, volume: f32) {
58 self.0.set_volume(volume);
59 }
60
61 pub fn pause(&self) {
62 self.0.pause();
63 }
64
65 pub fn resume(&self) {
66 self.0.play();
67 }
68
69 pub fn stop(&self) {
70 self.0.stop();
71 }
72
73 pub fn is_finished(&self) -> bool {
74 self.0.empty()
75 }
76}
77
78pub struct AudioOutput {
79 sink: rodio::MixerDeviceSink,
80}
81
82impl AudioOutput {
83 fn new() -> Result<Self, AudioError> {
84 let sink = rodio::DeviceSinkBuilder::open_default_sink().map_err(|e| AudioError::Device(e.to_string()))?;
85 Ok(Self { sink })
86 }
87
88 pub fn play(&self, sound: &Sound) {
89 let player = rodio::Player::connect_new(self.sink.mixer());
90 player.append(sound.0.clone());
91 player.play();
92 player.detach();
93 }
94
95 pub fn play_looped(&self, sound: &Sound) {
96 let player = rodio::Player::connect_new(self.sink.mixer());
97 player.append(sound.0.clone().repeat_infinite());
98 player.play();
99 player.detach();
100 }
101
102 pub fn play_controlled(&self, sound: &Sound) -> PlayingSound {
103 let player = rodio::Player::connect_new(self.sink.mixer());
104 player.append(sound.0.clone());
105 player.play();
106 PlayingSound(player)
107 }
108}
109
110pub struct AudioPlugin;
111
112impl Plugin for AudioPlugin {
113 fn build(self, app: crate::app::App) -> crate::app::App {
114 match AudioOutput::new() {
115 Ok(output) => app.insert_resource(output),
116 Err(e) => {
117 tracing::error!("AudioPlugin: failed to open the default audio output device: {e}");
118 app
119 }
120 }
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn from_file_on_a_missing_path_returns_a_real_err() {
130 let result = SoundBuilder::from_file("does/not/exist.wav");
131 assert!(result.is_err());
132 }
133
134 #[test]
135 fn from_file_decodes_a_valid_wav_fixture() {
136 let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/audio/tone.wav");
137 let sound = SoundBuilder::from_file(path).expect("fixture should decode cleanly");
138 assert!(sound.0.total_duration().is_some_and(|d| !d.is_zero()));
139 }
140}