1 use std::io::{Read, Seek}; 2 use std::time::Duration; 3 4 use Source; 5 6 use minimp3::{Decoder, Frame}; 7 8 pub struct Mp3Decoder<R> 9 where 10 R: Read + Seek, 11 { 12 decoder: Decoder<R>, 13 current_frame: Frame, 14 current_frame_offset: usize, 15 } 16 17 impl<R> Mp3Decoder<R> 18 where 19 R: Read + Seek, 20 { new(data: R) -> Result<Self, ()>21 pub fn new(data: R) -> Result<Self, ()> { 22 let mut decoder = Decoder::new(data); 23 let current_frame = decoder.next_frame().map_err(|_| ())?; 24 25 Ok(Mp3Decoder { 26 decoder, 27 current_frame, 28 current_frame_offset: 0, 29 }) 30 } 31 } 32 33 impl<R> Source for Mp3Decoder<R> 34 where 35 R: Read + Seek 36 { 37 #[inline] current_frame_len(&self) -> Option<usize>38 fn current_frame_len(&self) -> Option<usize> { 39 Some(self.current_frame.data.len()) 40 } 41 42 #[inline] channels(&self) -> u1643 fn channels(&self) -> u16 { 44 self.current_frame.channels as _ 45 } 46 47 #[inline] sample_rate(&self) -> u3248 fn sample_rate(&self) -> u32 { 49 self.current_frame.sample_rate as _ 50 } 51 52 #[inline] total_duration(&self) -> Option<Duration>53 fn total_duration(&self) -> Option<Duration> { 54 None 55 } 56 } 57 58 impl<R> Iterator for Mp3Decoder<R> 59 where 60 R: Read + Seek 61 { 62 type Item = i16; 63 64 #[inline] next(&mut self) -> Option<i16>65 fn next(&mut self) -> Option<i16> { 66 if self.current_frame_offset == self.current_frame.data.len() { 67 self.current_frame_offset = 0; 68 match self.decoder.next_frame() { 69 Ok(frame) => self.current_frame = frame, 70 _ => return None, 71 } 72 } 73 74 let v = self.current_frame.data[self.current_frame_offset]; 75 self.current_frame_offset += 1; 76 77 return Some(v); 78 } 79 }