Technical Q&A QA1913

Accessing Audio Files in Asset Catalogs

Q:  How do I add and access audio files stored in asset catalogs?

A: Asset catalogs allow you to manage your app resources. They can include files such as icons, images, audio and video files, and watch complications. See Xcode Help > Work with Assets > Asset Catalogs for more information about asset catalogs.

How do I add an audio file to an asset catalog?

Asset catalogs use data sets to create and manage audio files. See Xcode Help > Work with Assets > Asset Catalogs > Create a data set for more information on how to use them to add your audio files as shown in Figure 1.

Figure 1  Sound data asset that contains an audio file.

How do I access an audio file stored in an asset catalog?

The NSDataAsset class allows you to access an object from a data set stored in an asset catalog. Create and initialize an instance of NSDataAsset with your data set's name, then use its data property to access your audio file in the asset catalog as shown in Listing 1.

Listing 1  Accessing and playing an audio file stored in the Sound data set

import AVFoundation
 
var player: AVAudioPlayer?
 
 @IBAction func play(_ sender: UIButton){
    // Fetch the Sound data set.
    if let asset = NSDataAsset(name:"Sound"){
 
       do {
             // Use NSDataAsset's data property to access the audio file stored in Sound.
              player = try AVAudioPlayer(data:asset.data, fileTypeHint:"caf")
             // Play the above sound file.
             player?.play()
       } catch let error as NSError {
             print(error.localizedDescription)
       }
    }
 }


Document Revision History


DateNotes
2016-10-31

Fixed typo in code listing. Updated for Xcode 8.

2015-12-26

New document that describes how to add and access audio files stored in asset catalogs.