我尝试使背景音乐无缝循环,同时有一个不循环的部分,但切换AVAudioPlayers时会有延迟。当songA停止并且songB开始时发生延迟。 这是代码。
lazy var songA: AVAudioPlayer? = {
guard let url = Bundle.main.url(forResource: "A", withExtension: "wav") else {
return nil
}
do {
let player = try AVAudioPlayer(contentsOf: url)
let x = player
x.delegate=self
player.numberOfLoops = 0
player.prepareToPlay()
return player
} catch {
return nil
}
}()
lazy var songB: AVAudioPlayer? = {
guard let url = Bundle.main.url(forResource: "B", withExtension: "wav") else {
return nil
}
do {
let player = try AVAudioPlayer(contentsOf: url)
player.numberOfLoops = -1
player.prepareToPlay()
return player
} catch {
return nil
}
}()
func multiTrack(songA: AVAudioPlayer, songB: AVAudioPlayer) {
masterStop()
songA.play()
while songA.isPlaying==true {
if songA.isPlaying==false{
songB.play()
songA.stop()
songA.prepareToPlay()
}
}
songB.play()
songA.stop()
songA.prepareToPlay()
songA.currentTime=0
}