import java.io.File;
import java.io.FileOutputStream;
import net.beadsproject.beads.analysis.featureextractors.BasicDataWriter;
import net.beadsproject.beads.analysis.featureextractors.FFT;
import net.beadsproject.beads.analysis.featureextractors.GnuplotDataWriter;
import net.beadsproject.beads.analysis.featureextractors.PeakDetector;
import net.beadsproject.beads.analysis.featureextractors.PowerSpectrum;
import net.beadsproject.beads.analysis.featureextractors.SpectralDifference;
import net.beadsproject.beads.analysis.segmenters.ShortFrameSegmenter;
import net.beadsproject.beads.core.AudioContext;
import net.beadsproject.beads.core.Bead;
import net.beadsproject.beads.data.Sample;
import net.beadsproject.beads.data.SampleManager;
import net.beadsproject.beads.events.AudioContextStopTrigger;
import net.beadsproject.beads.ugens.DelayTrigger;
import net.beadsproject.beads.ugens.Gain;
import net.beadsproject.beads.ugens.SamplePlayer;

public class FreshOnsetDetectorTest {

	
	public static void main(String[] args) throws Exception {
		final AudioContext ac = new AudioContext();
		//set up playback
		final Sample samp = SampleManager.sample("audio/01 Get Up.aif");
		SamplePlayer player = new SamplePlayer(ac, samp);
		Gain sampleTrack = new Gain(ac, samp.getNumChannels());
		sampleTrack.addInput(player);
		ac.out.addInput(sampleTrack);
		//set up extractor stuff
		ShortFrameSegmenter sfs = new ShortFrameSegmenter(ac);
		FFT fft = new FFT();
		PowerSpectrum ps = new PowerSpectrum();
		SpectralDifference sd = new SpectralDifference(ac.getSampleRate());
		PeakDetector pd = new PeakDetector();
		//connect extractor stuff
		sfs.addListener(fft);
		fft.addListener(ps);
		ps.addListener(sd);
		sd.addListener(pd);
		//connect audio to extractor
		ac.out.addDependent(sfs);
		sfs.addInput(ac.out);
		//record some data
		ps.addListener(new GnuplotDataWriter<float[]>(new FileOutputStream(new File("/Users/ollie/Desktop/psData"))));
		sd.addListener(new GnuplotDataWriter<Float>(new FileOutputStream(new File("/Users/ollie/Desktop/sdData"))));
		//set time limit
		DelayTrigger dt = new DelayTrigger(ac, 3000f, new AudioContextStopTrigger(ac));
		ac.out.addDependent(dt);
		//also make a click if you like
		pd.addMessageListener(new Bead() {
			public void messageReceived(Bead message) {
				System.out.println("click");
			}
		});
		//go
		ac.start();
	}
}
