AVMutableAudioMix - Can't fade out

1.2k views Asked by At

I'm trying to fade out a AVComposition track (its an audio track for a video).

I can fade it up at the start no problem, but am having a lot of trouble fading it out at the end. Here is my code:

AVMutableAudioMixInputParameters *audioMixParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:compositionAudioTrack];

[audioMixParameters setVolume:0.0 atTime:kCMTimeZero];
[audioMixParameters setVolumeRampFromStartVolume:0.0 toEndVolume:1.0 timeRange:CMTimeRangeMake(kCMTimeZero, CMTimeMake(150, kVideoFPS))];

CMTime fadeOutBegin = CMTimeMake((length - 5) * kVideoFPS, kVideoFPS);
[audioMixParameters setVolumeRampFromStartVolume:1.0 toEndVolume:0.0 timeRange:CMTimeRangeMake(fadeOutBegin, totalDuration)];

AVMutableAudioMix *audioMix = [AVMutableAudioMix audioMix];
audioMix.inputParameters = [NSArray arrayWithObject:audioMixParameters];

length is a NSUInteger which is the length of the video in seconds.

totalDuration is a CMTime of the total video's duration with a timescale of kVideoFPS

kVideoFPS is a constant with the value 30

My goal is to begin the fade out 5 seconds from the end of the composition. I have tried all sorts of things, like CMTimeMakeWithSeconds. I have also reversed the values of the fade in, and it works fine (fading the volume from 1.0 to 0.0 right at the start).

Any thoughts greatly appreciated!

2

There are 2 answers

0
Jeff C. On

For those who are running into trouble using AVAudioMix / AVMutableAudioMix in conjunction with with streaming media, note that per Apple it currently only supports file-based assets.

Source:

https://developer.apple.com/library/content/qa/qa1716/_index.html

(near the bottom of the tech note)

0
smg On

The second parameter of CMTimeRangeMake is the duration of the CMTimeRange, not the end time of the time range (ref):

CMTimeRange CMTimeRangeMake(CMTime start, CMTime duration);

Try this to fade out for the final 5 seconds of the composition:

CMTime fadeOutEnd = CMTimeMake(5 * kVideoFPS, kVideoFPS);
[audioMixParameters setVolumeRampFromStartVolume:1.0 toEndVolume:0.0 timeRange:CMTimeRangeMake(fadeOutBegin, fadeOutEnd)];