简体   繁体   中英

Limit audio duration when played

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 :)

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() .

作为音频工程师,我建议按照您想要的方式完全编辑音频,以避免编码时可能出现的任何不必要的伪像。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM