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