Slow start for AVAudioPlayer the first time a sound is played

后端 未结 9 1363
孤城傲影
孤城傲影 2020-12-02 09:23

I\'m trying to eliminate startup lag when playing a (very short -- less than 2 seconds) audio file via AVAudioPlayer on the iPhone.

First, the code:

         


        
9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 10:00

    Here's a simple Swift extension to AVAudioPlayer that uses the play-and-stop at 0 volume idea presented in previous answers. PrepareToPlay() unfortunately at least for me did not do the trick.

    extension AVAudioPlayer {
        private func initDelaylessPlayback() {
            volume = 0
            play()
            stop()
            volume = 1
        }
    
        convenience init(contentsOfWithoutDelay : URL) throws {
            try self.init(contentsOf: contentsOfWithoutDelay, fileTypeHint: nil)
            initDelaylessPlayback()
        }
    }
    

提交回复
热议问题