I don't understand why she does this: player = aPlayer; play?.play()

    func play(_ name: String){
        guard
            let url = Bundle.main.url(forResource: name, withExtension: "wav"),
            let _ = try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: []),
            let _ = try? AVAudioSession.sharedInstance().setActive(true),
            let aPlayer = try? AVAudioPlayer(contentsOf: url)
            else { return }
        player = aPlayer         // ???
        player?.play()
    }

why player = aPlayer?

The whole blog post

and tweet

... ping @Erica_Sadun? Though it's not illegal move anyway, plus if you want to retain aPlayer to prevent deallocation, that's one way to do it (IIUC that you're asking about the extra assignment).

You’re asking why not just aPlayer?.play() instead of these two lines?

why do player = aPlayer before player?.play(), why cannot just player?.play()? Especially AVAudioPlayer is a class...

Without the assignment player is an undefined symbol.

Even if, you mean, aPlayer.play(), it'd get destroyed once the function ends.

2 Likes

So she is make sure to keep player alive for some reason I like to know, perhaps due to something about AVAudioPlayer...

Seems this should do the same:

       player = aPlayer               // keep this thing alive?
        aPlayer?.play()               // can use aPlayer, same as player now.

Must be due to some AVFoundation inner working needing to keep a AVAudioPlayer alive?

Not knowing the full source of the class, I am guessing that player is a property of the class that it being cached for other uses.

I would bet money the sound gets cut off if the object is deinited before it's done.

2 Likes

Strong reference that outlasts the life of the method so the full audio can finish playing.

Also I wrote that code in like 5 minutes. It makes me cringe looking at some of the style issues.

4 Likes