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
use rodio::Sink;

use crate::{audiobuffer::AudioBuffer, TerrasoundSource};

#[derive(Debug)]
pub enum AudioSourceError {
    NoMoreAudio,
}

pub struct AudioSource {
    pub buffers: Vec<AudioBuffer>,
    pub current_buffer_idx: usize,
    pub sink: Sink,
}

impl TerrasoundSource for AudioSource {
    fn get_next(&mut self) -> Result<AudioBuffer, AudioSourceError> {
        let buff_res = &self.buffers.get(self.current_buffer_idx);
        if buff_res.is_none() {
            return Err(AudioSourceError::NoMoreAudio);
        }

        self.current_buffer_idx += 1;
        Ok(buff_res.unwrap().clone())
    }

    fn play_next(&mut self) {
        let next_buffer = self.get_next().unwrap().clone();
        let sink = &self.sink;
        next_buffer.play(sink);
    }
}

impl AudioSource {
    pub fn add_buffer(&mut self, buffer: AudioBuffer) {
        self.buffers.push(buffer);
    }
}