Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

swift - AVAudioPlayer Intermittent Start Delay

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.

question from:https://stackoverflow.com/questions/65647501/avaudioplayer-intermittent-start-delay

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...