3

I did a basic implementation of an AVAudioPlayer:

do {
    try AVAudioSession.sharedInstance().setMode(.default)
    try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
    
    guard let urlStringBoltDown = urlStringBoltDown else {
        return
    }
    
    player4 = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: urlStringBoltDown))
    
    guard let player4 = player4 else {
        return
    }
    
    player4.prepareToPlay()
    
} catch {
    print("oops")
}

When playing the sound (about .5 seconds long), I have both delay and lag. With the help of this question I managed to get rid of the lag:

DispatchQueue.global().async {
    self.player4?.play()
}

Despite calling player4.prepareToPlay() (as suggested in multiple answers, for example: link) right after the initialisation in ViewDidLoad() I still get a delay on the first run (about 2 seconds). This delay does disappear after playing the sound once, but not permanently. If I play the sound again on this particular player or any other in about 3 seconds, there is no delay. Otherwise, it reappears.

I tried:

  • calling prepareToPlay() after every sound played (nothing)
  • calling prepareToPlay() in ViewDidAppear() (nothing)
  • playing and the stopping the player after every sound (suggested here). Again, this removed the delay for every .play() in the next 3 seconds or so, anything after having the same delay

It would be really helpful if I could check whether the player is actually ready to play or not after calling prepareToPlay(), but I only found methods of checking an AVPlayer status. If someone could point out how to do this I might solve the problem or at least add some valuable information to this question.

I just want a way to remove the delay permanently. Any help would be greatly appreciated.

  • Started a bounty, thanks for asking this question. This is happening to my app only when playing AVAudioPlayer files over a bluetooth speaker. It doesn't happen for me over the device speaker, or AirPods. – Joshua Hart Mar 25 '21 at 03:40
  • @JoshuaHart generally, bluetooth latency is a feature, and you better asking your question separately, detailing your app scenario, bluetooth version, audio codec, device manufacturer. – paiv Mar 25 '21 at 05:21
  • 1
    Have you tried to instantiate an AVAudioPlayer in a private queue? That seems to be a pretty resource consuming operation. Take a look at Mocha's answer here: https://stackoverflow.com/questions/25503629/avaudioplayer-produces-lag-despite-preparetoplay-in-swift – Artem Garmash Mar 28 '21 at 16:00

0 Answers0