tesselode / kira

Library for expressive game audio.
https://crates.io/crates/kira
Apache License 2.0
836 stars 42 forks source link

Build StaticSoundData from buffer #44

Closed dcvz closed 1 year ago

dcvz commented 1 year ago

Hello all,

I’m attempting to use this in a game (more similar to an emulator) where I’m receiving audio data in a u8 buffer. I tried looking around but it seems there’s no real way of creating a sound data object that I can just send off to play. I already know the num of channels and rate.

It could also be this library isn’t meant to be used this way. Any help would be appreciated :)

dcvz commented 1 year ago

Trying do something like this now (inspired by the from_file source) - but getting choppy sound. So I guess this is the way just gotta get the conversion right.

let buffer = buf.to_vec();
let mut frames = vec![];

for i in (0..buffer.len()).step_by(4) {
    let left = i16::from_le_bytes([buffer[i], buffer[i + 1]]);
    let right = i16::from_le_bytes([buffer[i + 2], buffer[i + 3]]);
    frames.push(Frame::new(left.into(), right.into()));
}

let sound_data = StaticSoundData {
    sample_rate: 44_100,
    frames: Arc::new(frames),
    settings: StaticSoundSettings::default(),
};
tesselode commented 1 year ago

To be clear, the audio bytes weren't an existing audio file format, like wav or mp3, right?

dcvz commented 1 year ago

To be clear, the audio bytes weren't an existing audio file format, like wav or mp3, right?

They were not, no. It was audio produced in engine from other file formats. Think an emulator. I couldn’t get it to not be choppy and in the end went with using cpal directly but it might still be a use case for others - since using cpal has a higher entrance barrier.