Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping AVAudioPlayer at a certain time in Swift

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.

like image 452
JSpicky Avatar asked Oct 22 '25 04:10

JSpicky


1 Answers

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()
    }
}
like image 89
Wez Avatar answered Oct 23 '25 20:10

Wez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!