Question: I'm trying to build an iOS application using Swift 4 that would play different sounds. Part of what I need to do is to limit the duration of the sound file played depending on some settings. 

What I'd like to know is if it's possible to set the duration of the sound prior to playing it so it can stop after the set duration. If so, how? 

I'm currently using Swift's *AVAudioPlayer* but I don't know if it can do it. My current code is shown below:

```
// resName set depending on settings

url = Bundle.main.url(forResource: resName, withExtension: "mp3")

do{
    audioPlayer = try AVAudioPlayer(contentsOf: url!)
    audioPlayer.prepareToPlay()
    audioPlayer.currentTime = 0
} catch let error as NSError{
    print(error.debugDescription)
}

audioPlayer.play()

```

Thanks in advance for the help :)

Answer: 
Well, since you are in control of playing the sounds, one way how to deal with it would be running a `Timer` when you start playing that would after the given time period stop playing:

```
let timeLimit = 1.6 // get it from settings
player.play()
Timer.scheduledTimer(withTimeInterval: timeLimit, repeats: false) { (timer) in
    player.stop()
}

```

And in case you need to cancel it, you can keep a reference to the `timer` and cancel it using `timer.invalidate()`.
As an audio engineer, I recommend editing your audio to be exactly how you want it to avoid any unwanted artifacts that can happen from coding.