Playing audio is an important part of many apps. One common trick is to fade in the volume of audio playback so we donโ€™t surprise or startle the user. This year, Apple has made this much simpler to implement using . Letโ€™s take a look.

First weโ€™ll set up a standard AVAudioPlayer, and begin playing it at a volume of 0:

guard let asset = NSDataAsset(name: "alarm") else { print("Error Loading Audio."); return }

let player: AVAudioPlayer

do {
  player = try AVAudioPlayer(:
} catch { print("Error Playing."); return }

player.volume = 0
player.numberOfLoops = -1

At this point the audio is playing but we canโ€™t hear it.

Before we check out the new feature, letโ€™s review the โ€œoldโ€ way we might do this.

Before , macOS ., and tvOS , fading this audio in was, well, letโ€™s just call it โ€œverboseโ€:

func fadeInPlayer() {
  if player.volume <= 1 - fadeVolumeStep {
    player.volume += fadeVolumeStep
    dispatchAfterDelayHelper(: fadeVolumeStepTime) { fadeInPlayer() }
  } else {
    player.volume = 1


Recursive functions, GCD delays, manually managing state. Yuck.

Thankfully, thereโ€™s now a better way.

Hereโ€™s all it takes:

player.setVolume(1, fadeDuration: 1.5)

This single line of code will fade in the audio from our initial volume of 0 up to 1 over a period of 1.5 seconds.



Source link


Please enter your comment!
Please enter your name here