Folks,
As far as I'm aware there isn't a built-in way of fading sounds in Gideros. So, following my often quipped mantra that one can
Tween Anything, here are some simple additions to SoundChannel to allow you to fade sounds in and out.
SoundChannel.___set=SoundChannel.set
function SoundChannel:set(param, value)
if param=="volume" then
self:setVolume(value)
elseif param=="pitch" then
self:setPitch(value)
else
SoundChannel.___set(self, param, value)
end
return self
end
SoundChannel.___get=SoundChannel.get
function SoundChannel:get(param, value)
if param=="volume" then
return self:getVolume()
end
if param=="pitch" then
return self:getPitch()
end
return SoundChannel.___get(self, param, value)
end
function SoundChannel:fadeIn(duration, optFinalLevel, completionFunc)
self:setVolume(0)
GTween.new(self, duration, { volume=optFinalLevel or 1 }, { onComplete=completionFunc })
end
function SoundChannel:fadeOut(duration, optFinalLevel, completionFunc)
GTween.new(self, duration, { volume=optFinalLevel or 0 }, { onComplete=
function()
self:stop()
if completionFunc then completionFunc() end
end
})
end |
So, with these methods in place you can do stuff like this:
local music=Sound.new("MyMusic.mp3")
local channel=music:play()
channel:fadeIn(3, 1, function() print("fade in complete") end)
--
-- Later
--
channel:fadeOut(3) |
Note that SoundChannel:fadeOut() can also take the same additional parameters as fadeIn(), I'm just showing that you can default these if you wish. Oh, and you can also tween the pitch of (non-music) sounds too. I haven't tried it but it might be interesting to play with.
You can either use the code above, or take my
BhHelpers library from GitHub.
best regards
Comments
In retrospect, I think that it would be more symmetrical if fadeOut() didn't call stop() and left this up to the caller if it is required. That would make fadeOut() simply:
I like a FadeOut(duration [, and_stop]) better.
FadeTo(volume,duration) functionality is about 2-3 functions or so even without GTween. Beats me why it is not native to Gideros ("you can write it yourself" doesn't count).