I would like to activate a function after a sound is played and complete. I assume that NSTimer needs to be included, but I am not sure of how to implement in order to make it. It is helpful if you could give me some code that works.
Asked
Active
Viewed 72 times
1 Answers
5
You should post code that you tried, and then someone then can help you make the code work. In this case, you don't need a timer for what you're doing. The AVAudioPlayerDelegate
protocol on the player was designed for what you are trying to do:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioPlayer:AVAudioPlayer?
func playSound(fileName:NSString)
{
let path = NSBundle.mainBundle().pathForResource(fileName, ofType:"wav")
let url = NSURL.fileURLWithPath(path!)
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
audioPlayer?.delegate = self
audioPlayer?.play()
} catch {
print("Player not available")
}
}
//MARK : AVAudioPlayerDelegate
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
print("finished playing, do something else here")
}
}

David S.
- 6,567
- 1
- 25
- 45
-
1This is what I would recommend as well. The `AVAudioPlayerDelegate` `audioPlayerDidFinishPlaying(_, successfully:)` method is how you should invoke code when a sound finishes playing. – Duncan C Apr 24 '16 at 14:33