As I was trying to play sound in my timer app, I use AVFoundation
in the code. While I am able to hear the sound in simulator, but not in device. I wonder if I need to set something for the app to play sound in device?
Please find the below code for more information.
import AVFoundation
class timer {
var player: AVAudioPlayer = AVAudioPlayer()
// in viewdidload
let squishPath = NSBundle.mainBundle().pathForResource("ding", ofType: "wav")
let squishURL = NSURL(fileURLWithPath: squishPath!)
do {
try squishPlayer = AVAudioPlayer(contentsOfURL: squishURL)
squishPlayer.prepareToPlay()
} catch let err as NSError {
print(err.debugDescription)
}
squishPlayer.numberOfLoops = 0
}
I checked the file name is exactly and it is in the copy bounce resources.
I found the solution is to add the following to app delegate.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(AVAudioSessionCategoryPlayback)
try session.setActive(true)
} catch let error as NSError {
print("AVAudioSession configuration error: \(error.localizedDescription)")
}
return true
}
And this solves the problem of no sound on device, but strange thing is even if I didn't add these to app delegate, there is still sound in simulator.