7

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.

enter image description here 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?

matt
  • 515,959
  • 87
  • 875
  • 1,141
user2924482
  • 8,380
  • 23
  • 89
  • 173

2 Answers2

13

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")!
matt
  • 515,959
  • 87
  • 875
  • 1,141
1

How to play audio from asset catalog

  1. create a new "data set" asset in your asset catalog (NOT an image asset)

  2. drag the audio file on it and name it correctly e.g. "mySound" (avoid names that are already used for image assets)

  3. 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)
        }
    } 
    
Jochen Holzer
  • 1,598
  • 19
  • 25