My book on iOS interface design, Design Teardowns: Step-by-step iOS interface design walkthroughs is now available!

Fading audio in and out

For one of those times we need to apply a fade in and out transition for audio playback, the AVPlayer API provides a possible way to do this:

let player = AVPlayer()

func playFileAtURL(url: NSURL) {  
    let asset = AVAsset.assetWithURL(url) as AVAsset

    let duration = asset.duration
    let durationInSeconds = CMTimeGetSeconds(duration)

    let item = AVPlayerItem(asset: asset)
    let params = AVMutableAudioMixInputParameters(track: asset.tracks.first! as AVAssetTrack)

    let firstSecond = CMTimeRangeMake(CMTimeMakeWithSeconds(0, 1), CMTimeMakeWithSeconds(1, 1))
    let lastSecond = CMTimeRangeMake(CMTimeMakeWithSeconds(durationInSeconds-1, 1), CMTimeMakeWithSeconds(1, 1))

    params.setVolumeRampFromStartVolume(0, toEndVolume: 1, timeRange: firstSecond)
    params.setVolumeRampFromStartVolume(1, toEndVolume: 0, timeRange: lastSecond)

    let mix = AVMutableAudioMix()
    mix.inputParameters = [params]
    item.audioMix = mix