extern crate dsp;
extern crate portaudio;
use dsp::{Graph, Frame, Node, FromSample, Sample};
use dsp::sample::ToFrameSliceMut;
use portaudio as pa;
const CHANNELS: usize = 2;
const FRAMES: u32 = 64;
const SAMPLE_HZ: f64 = 44_100.0;
fn main() {
run().unwrap()
}
fn run() -> Result<(), pa::Error> {
let mut graph = Graph::new();
let synth = graph.add_node(DspNode::Synth(0.0));
let (_, volume) = graph.add_output(synth, DspNode::Volume(1.0));
graph.set_master(Some(volume));
let mut timer: f64 = 0.0;
let mut prev_time = None;
let callback = move |pa::OutputStreamCallbackArgs { buffer, time, .. }| {
let buffer: &mut [[f32; CHANNELS]] = buffer.to_frame_slice_mut().unwrap();
dsp::slice::equilibrium(buffer);
graph.audio_requested(buffer, SAMPLE_HZ);
if let &mut DspNode::Volume(ref mut vol) = &mut graph[volume] {
*vol = (4.0 * timer as f32).sin() * 0.5;
}
let last_time = prev_time.unwrap_or(time.current);
let dt = time.current - last_time;
timer += dt;
prev_time = Some(time.current);
if timer <= 5.0 { pa::Continue } else { pa::Complete }
};
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS as i32, SAMPLE_HZ, FRAMES));
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stream.start());
while let Ok(true) = stream.is_active() {
::std::thread::sleep(::std::time::Duration::from_millis(16));
}
Ok(())
}
enum DspNode {
Synth(f64),
Volume(f32),
}
impl Node<[f32; CHANNELS]> for DspNode {
fn audio_requested(&mut self, buffer: &mut [[f32; CHANNELS]], sample_hz: f64) {
match *self {
DspNode::Synth(ref mut phase) => dsp::slice::map_in_place(buffer, |_| {
let val = sine_wave(*phase);
const SYNTH_HZ: f64 = 110.0;
*phase += SYNTH_HZ / sample_hz;
Frame::from_fn(|_| val)
}),
DspNode::Volume(vol) => dsp::slice::map_in_place(buffer, |f| f.map(|s| s.mul_amp(vol))),
}
}
}
fn sine_wave<S: Sample>(phase: f64) -> S
where S: Sample + FromSample<f32>,
{
use std::f64::consts::PI;
((phase * PI * 2.0).sin() as f32).to_sample::<S>()
}