From 2e4688a6a9f5a830754ce9dde1c54b5385048de4 Mon Sep 17 00:00:00 2001 From: Kostya Shishkov Date: Mon, 27 Apr 2020 10:33:10 +0200 Subject: [PATCH] make Wave writer output big-endian audio correctly --- src/wavwriter.rs | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/src/wavwriter.rs b/src/wavwriter.rs index fbf825d..a228876 100644 --- a/src/wavwriter.rs +++ b/src/wavwriter.rs @@ -8,6 +8,8 @@ use std::io::SeekFrom; pub struct WavWriter<'a> { io: Box>, data_pos: u64, + be: bool, + bits: u8, } fn write_byte(wr: &mut ByteWriter, sample: u8) -> ByteIOResult<()> { @@ -61,7 +63,7 @@ impl<'a> WavWriter<'a> { let file = File::create(name).unwrap(); let fw = Box::new(FileWriter::new_write(file)); let io = ByteWriter::new(Box::leak(fw)); - WavWriter { io: Box::new(io), data_pos: 0 } + WavWriter { io: Box::new(io), data_pos: 0, be: false, bits: 0 } } pub fn write_header(&mut self, ainfo: NAAudioInfo) -> ByteIOResult<()> { let bits = ainfo.get_format().get_bits() as usize; @@ -89,6 +91,8 @@ impl<'a> WavWriter<'a> { self.io.write_buf(b"data")?; self.io.write_u32le(0)?; + self.bits = bits as u8; + self.be = ainfo.get_format().is_be(); self.data_pos = self.io.tell(); Ok(()) } @@ -107,7 +111,35 @@ impl<'a> WavWriter<'a> { write_data!(&mut self.io, buf, write_f32); } NABufferType::AudioPacked(ref buf) => { - self.io.write_buf(buf.get_data().as_slice())?; + if !self.be || self.bits == 8 { + self.io.write_buf(buf.get_data().as_slice())?; + } else { + let data = buf.get_data(); + match self.bits { + 16 => { + for samp in data.chunks(2) { + self.io.write_byte(samp[1])?; + self.io.write_byte(samp[0])?; + } + }, + 24 => { + for samp in data.chunks(3) { + self.io.write_byte(samp[2])?; + self.io.write_byte(samp[1])?; + self.io.write_byte(samp[0])?; + } + }, + 32 => { + for samp in data.chunks(4) { + self.io.write_byte(samp[3])?; + self.io.write_byte(samp[2])?; + self.io.write_byte(samp[1])?; + self.io.write_byte(samp[0])?; + } + }, + _ => unimplemented!(), + }; + } } _ => {}, }; -- 2.39.5