I am trying to play sound when user enters background:
let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatchQueue, {[weak self] in
var audioSessionError: NSError?
let audioSession = AVAudioSession.sharedInstance()
NSNotificationCenter.defaultCenter().addObserver(self!, selector: "handleInterruption:", name: AVAudioSessionInterruptionNotification, object: nil)
audioSession.setActive(true, error: nil)
if (audioSession.setCategory(AVAudioSessionCategoryPlayback, error: &audioSessionError)) {
println("Successfully set the audio session")
} else {
println("Could not set the audio session")
}
let filePath = NSBundle.mainBundle().pathForResource("sound", ofType:"mp3")
let fileData = NSData(contentsOfFile: filePath!, options: .DataReadingMappedIfSafe, error: nil)
var error:NSError?
self!.audioPlayer = AVAudioPlayer(data: fileData, error: &error)
self!.audioPlayer?.numberOfLoops = -1
self!.audioPlayer?.delegate = self
if (self?.audioPlayer?.prepareToPlay() != false) {
println("Successfully prepared for playing")
} else {
println("Failed to prepare for playing")
}
})
if (self.audioPlayer?.play() != false) {
println("Successfully started playing")
} else {
println("Failed to Play")
}
Both player.prepareToPlay()
and player.play()
, they return true
. But actually there is no sound. If I run this anywhere else, it works. Help me please. I have added background audio mode.