Change a zone parameter randomly when pressing a key (with scripting)

Hello! I am trying to find a way to change a zone parameter when pressing a key on my midi keyboard. For example: When pressing a key, the grain duration parameter of the corresponding zone will change randomly. I know this is possible to do without scripting (using LFOs). This is just a way for me to learn scripting in Halion and what possibilities there are.

You can use the onNote callback together with setParameter

local zone = this.parent:getZone()

function onNote(e)
	zone:setParameterNormalized("Grain.Duration", math.random())
	postEvent(e)
end

Thank you, misohoza! When trying this with multiple samples mapped to different keys, only the first zone is affected, it seems. Is there a way to identify the specific zone that is triggered by that onNote?

Well, first of all there is a parameter called Duration Random which might do just what you want without any scripting.

But if you want to use script to change the grain duration or any other parameter for multiple zones you can use a loop.

local zones = this.parent:findZones(true)

function onNote(e)
	local rnd = math.random()
	for i, zone in ipairs(zones) do
		zone:setParameterNormalized("Grain.Duration", rnd)
	end
    postEvent(e)
end

That’s if you want the same random value for all zones. If you want a different value for each zone you can try:

local zones = this.parent:findZones(true)

function onNote(e)
	for i, zone in ipairs(zones) do
		zone:setParameterNormalized("Grain.Duration", math.random())
	end
    postEvent(e)
end

You could also create a table with some predefined values and pick randomly from them.

1 Like

I am sorry - grain duration serves as a bad example since it already has an inbuilt randomization function, as you mention. Other, more relevant examples would be speed and grain window. Anyway, thanks so much for your replies!