wav.rs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. extern crate find_folder;
  2. extern crate hound;
  3. extern crate portaudio as pa;
  4. fn main() {
  5. run().unwrap();
  6. }
  7. fn run() -> Result<(), pa::Error> {
  8. let mut samples = {
  9. let assets = find_folder::Search::ParentsThenKids(5, 5).for_folder("assets").unwrap();
  10. let sample_file = assets.join("amen_brother.wav");
  11. let mut reader = hound::WavReader::open(&sample_file).unwrap();
  12. reader.samples().collect::<Result<Vec<i16>, _>>().unwrap().into_iter()
  13. };
  14. let pa = try!(pa::PortAudio::new());
  15. const CHANNELS: i32 = 1;
  16. const SAMPLE_RATE: f64 = 44_100.0;
  17. const FRAMES_PER_BUFFER: u32 = 64;
  18. let settings = try!(pa.default_output_stream_settings(CHANNELS, SAMPLE_RATE, FRAMES_PER_BUFFER));
  19. let callback = move |pa::OutputStreamCallbackArgs { buffer, .. }| {
  20. for sample in buffer.iter_mut() {
  21. *sample = match samples.next() {
  22. Some(s) => s,
  23. None => return pa::Complete,
  24. };
  25. }
  26. pa::Continue
  27. };
  28. let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
  29. try!(stream.start());
  30. while let Ok(true) = stream.is_active() {}
  31. try!(stream.stop());
  32. try!(stream.close());
  33. Ok(())
  34. }