Skip to content

Instantly share code, notes, and snippets.

@artem-sherbachuk
Created January 19, 2017 09:43
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artem-sherbachuk/fc77395d58db8d1070500d307d6e74d1 to your computer and use it in GitHub Desktop.
Save artem-sherbachuk/fc77395d58db8d1070500d307d6e74d1 to your computer and use it in GitHub Desktop.
Fading audio in and out AVPlayer
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
player.replaceCurrentItemWithPlayerItem(item)
player.play()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment