9

I am trying to program an app that includes several songs. Looking through various tutorials they just say to "add your file to the project" or some such so I have tried adding my MP3 to various places (including xcassets) but it is never copied to the output of my project or played.

In other words, this always return nil:

let path = NSBundle.mainBundle().pathForResource(audioFile, ofType: "mp3")

This seems dead simple stuff and it is driving me crazy that it won't simply play the file. I have tried it in the root directory, a directory that I create named "resources" (since several sources say to "add it to resources"), and even in the xcassets. However, it always comes back nil.

Note that I am in Xcode 7 (the beta) developing for the latest iOS and using Swift 2. The file is about 53MB in size.

Any help is very much appreciated!

luk2302
  • 55,258
  • 23
  • 97
  • 137
Mark Brittingham
  • 28,545
  • 12
  • 80
  • 110
  • 1
    In newer versions, the code would be `let path = Bundle.main.path(forResource: audioFile, ofType: "mp3")` – Flimm Sep 23 '16 at 14:50

1 Answers1

17

It really is that simple. The only thing that you might have missed is that audioFile should really only contain the name, not the file extension. But beyond that it is as easy as dragging the file into your project and you can play it.

In the following gif I have code that plays an audio file and does some manipulation to answer this question. But basically it just loads an audio file the same way you try it.

  • I run the program at first to show that is in fact crashing without the file
  • Then I dragged the file into Xcode
  • Running the app again works as expected

Screencast

Community
  • 1
  • 1
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • 1
    That has to be the most bizarre thing I've ever seen. It now works having just stepped away for an hour. The only thing I can think of is that I may have been copying the file first and then including it in the project rather than just dragging it in. BTW - that was really helpful going through the trouble of making that GIF. I truly appreciate it. – Mark Brittingham Nov 29 '15 at 22:10
  • @MarkBrittingham you are welcome, always wanted to try this tool out - this seemed like an okay situation for it, its just better than words. – luk2302 Nov 29 '15 at 22:12