Skip to main content

sb3_decoder/model/
sound.rs

1use crate::Error;
2
3/// The representation of a Scratch sound inside a sprite.
4#[derive(Clone)]
5#[non_exhaustive]
6pub struct Sound {
7    pub name: String,
8    pub data_format: SoundFormat,
9
10    /// Raw file data. Enable the `sounds` feature to decode it.
11    pub data: Vec<u8>,
12}
13
14impl std::fmt::Debug for Sound {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        let Self {
17            name,
18            data_format,
19            data,
20        } = self;
21
22        f.debug_struct("Costume")
23            .field("name", name)
24            .field("data_format", data_format)
25            .field("data_len", &data.len())
26            .finish()
27    }
28}
29
30/// The sound format the sound is stored in.
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum SoundFormat {
34    Wav,
35    Mp3,
36}
37
38#[cfg(feature = "sounds")]
39impl Sound {
40    /// Decodes the audio data inside this costume.
41    pub fn decode(&self) -> Result<DecodedSound, Error> {
42        match self.data_format {
43            SoundFormat::Wav => self.decode_wav(),
44            SoundFormat::Mp3 => self.decode_mp3(),
45        }
46    }
47
48    pub fn decode_wav(&self) -> Result<DecodedSound, Error> {
49        use hound::{WavReader, WavSpec};
50
51        let wav_reader = WavReader::new(&self.data[..]).map_err(Error::hound)?;
52        let WavSpec {
53            sample_rate,
54            channels,
55            ..
56        } = wav_reader.spec();
57        let samples: Vec<_> = wav_reader
58            .into_samples::<i16>()
59            .collect::<Result<_, _>>()
60            .map_err(Error::hound)?;
61
62        Ok(DecodedSound {
63            sample_rate,
64            channels,
65            samples,
66        })
67    }
68
69    pub fn decode_mp3(&self) -> Result<DecodedSound, Error> {
70        use nanomp3::Reader;
71        use std::io::Cursor;
72
73        let cursor = Cursor::new(&self.data[..]);
74        let mut mp3_reader: Reader<_, i16> = Reader::new(cursor).map_err(Error::nanomp3)?;
75        let sample_rate = mp3_reader.sample_rate();
76        let channels = mp3_reader.channels().ok_or(Error::SoundEmpty)?.num() as u16;
77
78        let mut samples = Vec::new();
79        let mut buf = [0i16; 4096];
80
81        loop {
82            match mp3_reader.read(&mut buf).map_err(Error::nanomp3)? {
83                0 => break,
84                n => samples.extend_from_slice(&buf[..n]),
85            }
86        }
87
88        Ok(DecodedSound {
89            sample_rate,
90            channels,
91            samples,
92        })
93    }
94}
95
96/// A decoded sound file.
97#[cfg(feature = "sounds")]
98pub struct DecodedSound {
99    pub sample_rate: u32,
100    pub channels: u16,
101    pub samples: Vec<i16>,
102}