Accessing audio (and other) files stored in the Xcode asset catalog with Swift
When working on my "Nap Slide" iOS app, I needed to embed various .wav files in the application. Being new to iOS development, using the asset catalog seemed to be the obvious choice (Google/StackOverflow has led me to believe developers with previous Xcode experience would use application bundles).
Accessing images stored in the asset catalog is easy and well documented, accessing other file types (a feature added as of Xcode 7) is not. If like me you searched the 2015 WWDC session videos for hints - you didn't find much as it wasn't talked about in depth.
The key class to accessing non-image data you can store in the asset catalog is NSDataAsset.
Swift Example
// this call will play an asset named "click" and is stored in the asset catalog
playSound("click")
func playSound(nameOfAudioFileInAssetCatalog: String) {
private var alarmAudioPlayer: AVAudioPlayer?
if let sound = NSDataAsset(name: nameOfAudioFileInAssetCatalog) {
do {
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try! AVAudioSession.sharedInstance().setActive(true)
try alarmAudioPlayer = AVAudioPlayer(data: sound.data, fileTypeHint: AVFileTypeWAVE)
alarmAudioPlayer!.play()
} catch {
print("error initializing AVAudioPlayer")
}
}
}
Tagged Swift , Xcode and iOS