6

I have a data set of audio files in my Assets.xcassets:

Assets.xcassets

I'm trying to get the path of one of those audio files like this:

let path: String = Bundle.main.path(forResource: "acoustic_grand_piano/A4", ofType: "f32")!

But I get a EXC_BAD_INSTRUCTION. I tried to look on the internet but I don't find anything on Data Sets.

How can I get the content of one of these files?

Thanks!

Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56

1 Answers1

2

Try this:

  • Manually put your files into a folder, named anything you want.

  • Append ".bundle" to the folder to create a bundle. You'll get a warning, accept it. Congrats, you've just created your first bundle! :-)

  • Manually drag that folder into your app.

  • Get at your files by using the following code....

     public func returnFile(_ named:String) -> String {
         let path: String = Bundle.main.path(forResource: "myAudioFiles", ofType: "bundle")! + "/" + name + ".f32"        
         do {
             return try String(contentsOfFile: path)
         }
         catch let error as NSError {
             return error.description
         }
     }
    

Now, my files are text files of CIKernel code. Since your's are audio files you may need to change the String return to something else.

EDIT:

In my case I'm using a framework, as I wish to share these files/images with extensions and other apps. If you are working in such a set up, here's the unaltered code:

public func returnFile(_ resource:String, _ fileName:String, _ fileType:String) -> String {
    let identifier = "com.companyname.appname" // replace with framework bundle identifier
    let fileBundle = Bundle.init(identifier: identifier)
    let filePath = (fileBundle?.path(forResource: resource, ofType: "bundle"))! + "/" + fileName + "." + fileType
    do {
        return try String(contentsOfFile: filePath)
    }
    catch let error as NSError {
        return error.description
    }
}
Saeid
  • 2,261
  • 4
  • 27
  • 59