Reputation: 101
There is a playAtTime function in Swift, which allows you to specify any time when you want to start playing. I need to find a way to do the opposite thing. Is there any function that allows you to specify the time when you want a player to stop?
Upvotes: 2
Views: 1526
Reputation: 386
Leo's code above is now outdated for Swift 5. I used the following code with AVAudioPlayer to stop the audio at a predetermined time. You may be interested to know that the timer interval also works with milliseconds, with a resolution of about 0.1 to 0.05 seconds.
Here's the code I incorporated into my audio player class:
var audioPlayerTimer = Timer()
And in the function that I want to call to set the play interval:
audioPlayerTimer = Timer.scheduledTimer(timeInterval: 3.2, target: self, selector: #selector(self.pauseAudio), userInfo: nil, repeats: false)
You'll note that I have a separate function called pauseAudio. You need to have @objc in front of that function so that it recognizes it in the above code:
@objc func pauseAudio() {
guard let audioPlayer = audioPlayer else { return }
audioPlayer.pause()
}
You can pass variables to make the timeInterval a different number. Just send it as a Double.
Upvotes: 0
Reputation: 236260
You just have to set up a timer to fire after x seconds and add a method to stop your audio as follow:
var audioPlayerTimer = NSTimer()
audioPlayer.play()
audioPlayerTimer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: "stopAfter3seconds", userInfo: nil, repeats: false)
func stopAfter3seconds(){
audioPlayer.stop()
}
Upvotes: 4