I do something similar in the Moose script:
-- This function is called periodicly for each sound making entity
-- x,y is the position of the entity
-- Px, Py is player pos
-- Ent is the entity id (e iow) and num is the sound slot number
-- minVolume & volModifier are set to appropriate values, i.e. canopy open volModifier is 0, when
-- closed I set it to 13 to muffle the sounds.
-- minVolume is the squared distance at which the sound cuts off, I use 4000 * 4000.
local function SetVolume(Ent, num, x, z, Px, Pz)
local dx, dz = Px - x, Pz - z
local sqDist = dx*dx + dz*dz
local vol = minVolume - sqDist
if vol > 0 then
vol = 60 + (37 * (vol / minVolume)) - volModifier
else
vol = 0
end
SetSound(Ent, num)
SetSoundVolume(vol)
end
Been there, done that, got all the T-Shirts!