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.
Here is my code:
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?
A Sound Recording asset represents an audio recording, typically provided by a music label. The asset has metadata like ISRC, artist, and album, and a reference consisting of an audio master recording.
Click From SharePoint.Browse to a location on your site, such as an Assets Library, where video and audio files are saved. Select the file that you want, and then click Insert.
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")!
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With