Skip to content

Instantly share code, notes, and snippets.

@GGist
Last active October 11, 2015 01:35
Show Gist options
  • Save GGist/66fa64a6a3ea6e895409 to your computer and use it in GitHub Desktop.
Save GGist/66fa64a6a3ea6e895409 to your computer and use it in GitHub Desktop.
Playing WAV In rust-sdl2
extern crate sdl2;
use std::thread::{self};
use sdl2::{Sdl};
use sdl2::audio::{self, AudioSpecDesired, AudioSpecWAV, AudioCallback, AudioDevice};
//----------------------------------------------------------------------------//
struct CopiedData {
bytes: Vec<u8>,
position: usize
}
impl AudioCallback for CopiedData {
type Channel = u8;
fn callback(&mut self, data: &mut [u8]) {
let (start, end) = (self.position, self.position + data.len());
self.position += data.len();
let audio_data = &self.bytes[start..end];
for (src, dst) in audio_data.iter().zip(data.iter_mut()) {
*dst = *src;
}
}
}
//----------------------------------------------------------------------------//
struct WrappedData {
audio: AudioSpecWAV,
position: usize
}
impl AudioCallback for WrappedData {
type Channel = u8;
fn callback(&mut self, data: &mut [u8]) {
let (start, end) = (self.position, self.position + data.len());
self.position += data.len();
let audio_data = &self.audio.buffer()[start..end];
for (src, dst) in audio_data.iter().zip(data.iter_mut()) {
*dst = *src;
}
}
}
unsafe impl Send for WrappedData { }
//----------------------------------------------------------------------------//
pub fn main() {
let sdl_context = sdl2::init().unwrap();
let audio_system = sdl_context.audio().unwrap();
let audio_spec = AudioSpecDesired{ freq: None, channels: None, samples: None };
let audio_wav = AudioSpecWAV::load_wav("test.wav").unwrap();
let copied_data = CopiedData{ bytes: audio_wav.buffer().to_vec(), position: 0 };
//let wrapped_data = WrappedData{ audio: audio_wav, position: 0 };
let audio_device = audio_system.open_playback(None, audio_spec, move |spec| {
copied_data
}).unwrap();
audio_device.resume();
thread::sleep_ms(5000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment