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.
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)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With