How do I fade in and fade out a channel (with stop)

How can I fade in a sound when it starts playing, and fade out a sound when I want it to stop?

To do a 5 second fade in

After a playSound command, use the following code. For best results start the sound paused.

unsigned long long dspclock;
FMOD::System *sys;
int rate;

result = chan->getSystemObject(&sys);                        // OPTIONAL : Get System object
ERRCHECK(result);
result = sys->getSoftwareFormat(&rate, 0, 0);                // Get mixer rate
ERRCHECK(result);

result = chan->getDSPClock(0, &dspclock);                    // Get the reference clock, which is the parent channel group
ERRCHECK(result);
result = chan->addFadePoint(dspclock, 0.0f);                 // Add a fade point at 'now' with full volume.
ERRCHECK(result);
result = chan->addFadePoint(dspclock + (rate * 5), 1.0f);    // Add a fade point 5 seconds later at 0 volume.
ERRCHECK(result);

Now unpause the sound with chan->setPaused(false);

To do a 5 second fade out (and stop)

unsigned long long dspclock;
FMOD::System *sys;
int rate;

result = chan->getSystemObject(&sys);                        // OPTIONAL : Get System object
ERRCHECK(result);
result = sys->getSoftwareFormat(&rate, 0, 0);                // Get mixer rate
ERRCHECK(result);

result = chan->getDSPClock(0, &dspclock);                    // Get the reference clock, which is the parent channel group
ERRCHECK(result);
result = chan->addFadePoint(dspclock, 1.0f);                 // Add a fade point at 'now' with full volume.
ERRCHECK(result);
result = chan->addFadePoint(dspclock + (rate * 5), 0.0f);    // Add a fade point 5 seconds later at 0 volume.
ERRCHECK(result);
result = chan->setDelay(0, dspclock + (rate * 5), true);     // Add a delayed stop command at 5 seconds ('stopchannels = true')
ERRCHECK(result);

how can i set the fade out at the end of the sound file?

1 Like

You use the above fade out code, the only difference is, you have to work out in DSP clock time when your sound will end. You do that by getting the start time as above, add the length in samples of the sound divided by the default sample rate of the sound (ie Sound::getFormat), then multiplied by the output rate (System::getSoftwareFormat), subtract the rate*delay_in_seconds in this case to start the fadeout early for the first fade point.
You wouldn’t need the setDelay in this case as it will be stopping by itself.