Reputation: 65
So I am creating an iPhone app that downloads sound files in Swift and I had a question. Using Xcode and the iOS simulator, I'm able to successfully download the audio files that I need onto the simulator. I found that the files being downloaded are in this directory on my OSx machine:
OS X -> Users -> "My name" -> Library -> Developer -> CoreSimulator -> Devices -> 96CDD... -> data -> 6B742... -> Documents
Now my question is this, I know I have the audio files on the device inside of the app, but how do I access them and then play them from the app itself? I'm trying to just use AVAudioPlayer, but I've been unsuccessful in accessing the file. Here is the code I'm trying to run which is inside of the viewDidLoad function:
var playYoda = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Documents/do_or_do_not", ofType: "wav")!)
println(playYoda)
AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
AVAudioSession.sharedInstance().setActive(true, error: nil)
var error:NSError?
audioPlayer = AVAudioPlayer(contentsOfURL: playYoda, error: &error)
audioPlayer.prepareToPlay()
audioPlayer.play()
All of my code compiles, but when I start the simulator, I'm getting this error: fatal error: unexpectedly found nil while unwrapping an Optional value right at the first line of code that I linked (var playYoda = ...).
I don't know whether this is because my path is wrong to the audio file, or if I'm doing something wrong with AVAudioPlayer. Any help would be appreciated.
Upvotes: 4
Views: 9308
Reputation: 951
Here is what else you can do:
Open your Xcode project, select your audio files in the project navigator, and hit delete (make sure to move them to trash and not just remove references).
Then go File > Add files to "Your app".
Select your audio files you want to import and make sure that the defaults ("Copy items if needed", "Create groups", and "Add files to target: Your App") are checked.
For the file path write:
var playYoda = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("do_or_do_not", ofType: "wav")!)
Upvotes: 2
Reputation: 89509
How about something like:
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
if let documentDirectoryURL: NSURL = urls.first as? NSURL {
let playYoda = documentDirectoryURL.URLByAppendingPathComponent("do_or_do_not.wav")
println("playYoda is \(playYoda)")
}
Upvotes: 2