(
SynthDef(\hdpPlayer, {arg playBuf = 0, gate = 0;
	var playDur, fadeTime, changeTrig, playSig, fade;
	fadeTime = 30;
	playSig = PlayBuf.ar(2, playBuf, BufRateScale.kr(playBuf), gate, 0);
	fade = EnvGen.kr(Env.asr(fadeTime, 1, fadeTime), gate);
	Out.ar(0, playSig * fade);
	Out.ar([0, 1], BrownNoise.ar * 0.05 * (fade - 1).abs);
}).add;
);

(
var recDir, recPaths, recInfo, playBuf, player, isPlaying, playRoutine, localAddress;
recDir = "/home/mwinter/a_history_of_the_domino_problem/recs/";
recPaths = ["berger_knuth.wav", "robinson.wav", "penrose.wav", "ammann.wav", "kari_culik.wav", "jaendel_rao.wav"].collect({arg file; recDir +/+ file});
recInfo = recPaths.collect({arg path; var sndFile; sndFile = SoundFile.openRead(path); [sndFile.numFrames, sndFile.sampleRate]});
playBuf = Buffer.read(s, recPaths[0]);
//lock = false;
isPlaying = false;
player = Synth(\hdpPlayer, [\playBuf, playBuf]);
localAddress = NetAddr.new("127.0.0.1", 57120);

OSCFunc({ arg msg, time;
	[time, msg].postln;
	//lock.postln;
	playRoutine.stop;
	playRoutine = Routine({
		var playDur, piece, numPlayFrames, startFrame;
		if(isPlaying, {
			player.set(\gate, 0);
			30.wait;
		});
		isPlaying = true;
		piece = msg[1];
		playDur = (5.0.rand + 5) * 60;
		numPlayFrames = playDur * recInfo[piece][1];
		startFrame = (recInfo[piece][0] - numPlayFrames).rand;
		playBuf.free;
		playBuf = Buffer.read(s, recPaths[piece], startFrame, numPlayFrames, action: {arg buf;
			player.set(\gate, 1);
		});
		(playDur - 30).wait;
		player.set(\gate, 0);
		30.wait;
		isPlaying = false;
	}).play
},'/playTiling', localAddress);
)

n = NetAddr("127.0.0.1", 57120)
n.sendMsg('/playTiling', 1)

