young
(rtSwift)
June 5, 2020, 8:02pm
1
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).
toph42
(Topher Hickman)
June 5, 2020, 8:07pm
3
You’re asking why not just aPlayer?.play()
instead of these two lines?
young
(rtSwift)
June 5, 2020, 8:09pm
4
why do player = aPlayer
before player?.play()
, why cannot just player?.play()
? Especially AVAudioPlayer
is a class...
toph42
(Topher Hickman)
June 5, 2020, 8:14pm
5
Without the assignment player
is an undefined symbol.
Even if, you mean, aPlayer.play()
, it'd get destroyed once the function ends.
2 Likes
young
(rtSwift)
June 5, 2020, 8:45pm
7
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?
Alan
(Alan W)
June 5, 2020, 9:01pm
8
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