I'm playing an mp3 file stored in an iOS app's asset catalog & I'm declaring my AVAudioPlayer when I declare the player with app-wide scope. My code works fine, but I'd like to know if this is poor practice & if so, why. Most code examples playing audio declare an AVPlayer as an optional but don't create the player at declaration, like so:
var audioPlayer: AVAudioPlayer?
I implement below b/c doesn't have any references to optionals or forced unwrapping (I'm just ramping up in Swift myself, but I'm using this as an early "Get Excited" example for my students so they can have media playing back in one of their first apps. Hope to postpone optionals discussion 'til later).
// Declare AVAudioPlayer and assign an empty player
var audioPlayer = AVAudioPlayer()
// Call this function to play an mp3 sound in asset file named "sound0"
func playSound() {
if let sound = NSDataAsset(name: "sound0") {
do {
try audioPlayer = AVAudioPlayer(data: sound.data)
audioPlayer.play()
} catch {
print("ERROR: Couldn't create the AVAudioPlayer")
}
} else {
print("ERROR: Couldn't load sound file from asset catalog. Verify file is a valid sound file and that the name is correct.")
}
}
// Thanks!