sound from NSTimer not working

I'm trying to play a sound after the NSTimer has counted down, so far I know the selector is being called but for some reason no sound is playing.



let timer = NSTimer(fireDate: task.date, interval: 0, target: self, selector: Selector("update"), userInfo: nil, repeats: false)


NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)


func update() { 
backgroundMusic = self.setupAudioPlayerWithFile("music", type:"mp3")
 backgroundMusic.volume = 1 backgroundMusic.prepareToPlay() backgroundMusic.play() println("we made it!") 
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer { 
/ var path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
 var url = NSURL.fileURLWithPath(path!) 
var error: NSError? 
var audioPlayer:AVAudioPlayer? 
audioPlayer = AVAudioPlayer(contentsOfURL: url, error: &error) 
return audioPlayer! }


The timer works perfectly, it executes the function update and I know that because I always see the println in the console, but the sound never plays. Anyone know a solution? Or another method of getting the sound to play, i need the sound to play right after the timer finishes

Answered by OOPer in 42709022

I don't understand why you think "it makes a difference" without any basis, but it is very likely it makes difference.

I re-formatted your code and tested in a simple project.

And your update method very well played the sound file "music.mp3".


If your code does not work well, there's something bad in codes or settings that you have not shown.

For one possibility, how do you declared the backgroundMusic property? AVAudioPlayer does not play sounds if it is released before starting playing.

var backgroundMusic = AVAudioPlayer()


^ That's how I've declared it


I don't know if this makes a difference but once I click the save button it performs a segue to another view controller, I don't think it makes a difference with the sound going off, but thats about the only major change


I put it on github /KashishGoel/Kashish_TaskItiOSApp

The timer is under AddTaskViewController in the xcworkspace

Accepted Answer

I don't understand why you think "it makes a difference" without any basis, but it is very likely it makes difference.

sound from NSTimer not working
 
 
Q