Reputation: 9140
I'm trying to load/play an audio file store in the assets library but for some reason it can not be found in the bundle.
func playAudio() {
let path = Bundle.main.path(forResource: "sound", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
sound = try AVAudioPlayer(contentsOf: url)
sound?.play()
} catch {
// do something
}
}
Any of you knows what I'm doing wrong? or why Xcode can not find the file?
Upvotes: 10
Views: 5220
Reputation: 1736
How to play audio from asset catalog
create a new "data set" asset in your asset catalog (NOT an image asset)
drag the audio file on it and name it correctly e.g. "mySound" (avoid names that are already used for image assets)
play it via playAudioAsset("mySound")
using the code above
Class MyClass {
var audioPlayer: AVAudioPlayer!
...
func playAudioAsset(_ assetName : String) {
guard let audioData = NSDataAsset(name: assetName)?.data else {
fatalError("Unable to find asset \(assetName)")
}
do {
audioPlayer = try AVAudioPlayer(data: audioData)
audioPlayer.play()
} catch {
fatalError(error.localizedDescription)
}
}
Upvotes: 5
Reputation: 536047
but for some reason it can not be found in the bundle
Because it is not in the bundle. It is in the asset catalog.
Use the NSDataAsset class to fetch it.
let data = NSDataAsset(name: "sound")!
Upvotes: 14