How to start and stop a pbind with midi CC

I have a, hopefully simple, question.
How do i start and stop a Pbind with midi?
I can start this, but for some reason, it won’t stop again. Is the player variable out of scope for the second if statement block? Is there another way to approach this to make it work?
I know this is a simple question, but I didn’t manage to find it on the forum with search.
Thanks in advance
Anders

( var player, pattern = Pbind(\instrument, \sinGen, \freq, Pseq(Array.fill(8, { arg i; [3 * i + 110, 110, 4 * i + 111] }), 10));

MIDIdef.cc(\fPlay,
	{arg val, num, chan, src;
		if (num == 1, { player = pattern.play });
		if (num == 2, { player.stop })
});
)

Is it possible that you’re receiving two CC messages with num == 1 without an intervening num == 2?

In that case, you’d have a player that’s running, but already replaced in player by a second one. You could stop the last one but the first is unreachable.

I often do it like this – the player variable keeps track of the status. Your pattern will eventually end so some other trickery is involved to track the status.

(
var player, watcher;
var pattern = Pbind(
	\instrument, \sinGen,
	\freq, Pseq(Array.fill(8, { arg i;
		[3 * i + 110, 110, 4 * i + 111]
	}), 10)
);

MIDIdef.cc(\fPlay, { arg val, num, chan, src;
	if (num == 1 and: { player.isNil }, {
		player = pattern.play;
		watcher = SimpleController(player)
		.put(\stopped, {
			// pattern ended, clear the variable for next time
			player = nil;
			watcher.remove;  // don't forget this! important garbage collection!
		});
	});
	if (num == 2, {
		player.stop;  // will fire the 'watcher'
	})
});
)

hjh

1 Like

Thank you, that was excactly what was happening! My CC’s came with both a val == 127 and val == 0 message, so I triggered two Pbind’s as you say, and the first one is unreachable when the second one is triggered.
For anyone finding this later on, this code also works. Not as sofisticated and with no garbage collection, but I don’t know if it’s a problem here:

(
var player, pattern = f;

MIDIdef.cc(\fPlay,
	{arg val, num, chan, src;
		if (num == 1 && val == 127, { player = pattern.play });
		if (num == 7 && val == 127, { player.stop });
});
)