Reputation: 151
I'm trying to play a segment of a sound clip. How would I stop the AVAudioPlayer at a certain time?
I have a function that when called from a slider value, will set the playtime to a given place. (songStart and SongEnd are simply a percentage of the song) What function could I build to stop it at a certain point?
func setSongConstraints(songStart: Double, songEnd: Double){
audioPlayer.currentTime = audioPlayer.duration * songStart
}
I know an option would be to set a wait timer or something, and then call stop after that amount of time.
However, I'd like the function to allow for the end point of the song to be changed after the song starts. The wait timer wouldn't work in this instance, as it would need to be changed after it had started.
Upvotes: 4
Views: 5871
Reputation: 10712
You could use a Timer
to check the currentTime
property of your AVAudioPlayer
object.
For Example
Start the timer when you start playing the audio. Adjusting the check interval 0.1
based on the level of accuracy required.
var timer:Timer!
timer = Timer.scheduledTimerWithTimeInterval(
0.1,
target: self,
selector: "checkTime",
userInfo: nil,
repeats: true
)
Then create the function that the timer runs every 0.1
second to check the audio players current time against your own value where END_TIME
could be updated or replaced by your songEnd
logic.
let END_TIME = 10.0
func checkTime() {
if self.audioPlayer.currentTime >= END_TIME {
self.audioPlayer.stop()
timer.invalidate()
}
}
Upvotes: 8
Reputation: 270
You can use a wait timer. If the user resets the endpoint of the song, just reset the timer to to the new delta of - . You can do that by either killing the existing timer and spawning a new one, or changing the fireDate of the existing timer. Be sure to handle the condition where the new endpoint is earlier than the currentTime... then you should just call stop and kill the existing timer.
Upvotes: 1
Reputation: 16837
I know you do not want to do a wait timer, but you could always just keep track of how much time has lapsed and reset the timer when new data is available. Or I guess poll NSDate in some kind of loop.
Upvotes: 0