wav.rs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. extern crate find_folder; // For easily finding the assets folder.
  2. extern crate portaudio as pa; // For audio I/O
  3. extern crate pitch_calc as pitch; // To work with musical notes.
  4. extern crate sample; // To convert portaudio sample buffers to frames.
  5. extern crate sampler;
  6. use sampler::Sampler;
  7. const CHANNELS: i32 = 2;
  8. const SAMPLE_RATE: f64 = 44_100.0;
  9. const FRAMES_PER_BUFFER: u32 = 64;
  10. const THUMB_PIANO: &'static str = "thumbpiano A#3.wav";
  11. fn main() {
  12. run().unwrap();
  13. }
  14. fn run() -> Result<(), pa::Error> {
  15. // We'll create a sample map that maps a single sample to the entire note range.
  16. let assets = find_folder::Search::ParentsThenKids(5, 5).for_folder("assets").unwrap();
  17. let sample = sampler::Sample::from_wav_file(assets.join(THUMB_PIANO), SAMPLE_RATE).unwrap();
  18. let sample_map = sampler::Map::from_single_sample(sample);
  19. // Create a polyphonic sampler.
  20. let mut sampler = Sampler::poly((), sample_map).num_voices(4);
  21. // Initialise PortAudio and create an output stream.
  22. let pa = try!(pa::PortAudio::new());
  23. let settings =
  24. try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_RATE, FRAMES_PER_BUFFER));
  25. let callback = move |pa::OutputStreamCallbackArgs { buffer, .. }| {
  26. let buffer: &mut [[f32; CHANNELS as usize]] =
  27. sample::slice::to_frame_slice_mut(buffer).unwrap();
  28. sample::slice::equilibrium(buffer);
  29. // If the sampler is not currently active, play a note.
  30. if !sampler.is_active() {
  31. let vel = 0.3;
  32. sampler.note_on(pitch::LetterOctave(pitch::Letter::Ash, 3).to_hz(), vel);
  33. sampler.note_on(pitch::LetterOctave(pitch::Letter::Dsh, 3).to_hz(), vel);
  34. sampler.note_on(pitch::LetterOctave(pitch::Letter::Gsh, 1).to_hz(), vel);
  35. }
  36. sampler.fill_slice(buffer, SAMPLE_RATE);
  37. pa::Continue
  38. };
  39. let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
  40. try!(stream.start());
  41. while let Ok(true) = stream.is_active() {
  42. std::thread::sleep(std::time::Duration::from_millis(16));
  43. }
  44. try!(stream.stop());
  45. try!(stream.close());
  46. Ok(())
  47. }