user2924482
user2924482

Reputation: 9140

Playing audio in asset library

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?

Upvotes: 10

Views: 5220

Answers (2)

Jochen Holzer
Jochen Holzer

Reputation: 1736

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)
        }
    } 
    

Upvotes: 5

matt
matt

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

Related Questions