在AVAudioPlayer循环播放的时候,使用两个AVAudioPlayer对象交替播放,以达到无缝循环的效果。
代码示例:
var playerOne: AVAudioPlayer?
var playerTwo: AVAudioPlayer?
var activePlayer: AVAudioPlayer?
func playLoopedAudio() {
let url = Bundle.main.url(forResource: "loopedAudio", withExtension: "mp3")!
do {
playerOne = try AVAudioPlayer(contentsOf: url)
playerTwo = try AVAudioPlayer(contentsOf: url)
// 设置两个播放器循环播放
playerOne?.numberOfLoops = -1
playerTwo?.numberOfLoops = -1
// 将一个播放器设置为当前活动的播放器,开始播放
activePlayer = playerOne
activePlayer?.play()
} catch {
print("Unable to play looped audio: \(error.localizedDescription)")
}
}
func pauseLoopedAudio() {
activePlayer?.pause()
}
// 切换活动播放器
func switchActivePlayer() {
if activePlayer == playerOne {
activePlayer = playerTwo
} else {
activePlayer = playerOne
}
}
// 检测是否需要切换活动播放器
func checkForSwitchActivePlayer() {
let timeElapsed = activePlayer?.currentTime ?? 0.0
let duration = activePlayer?.duration ?? 0.0
let timeRemaining = duration - timeElapsed
// 如果当前播放器还剩下1秒以下的时间,就切换到另一个播放器,保证无缝循环
if timeRemaining < 1.0 {
switchActivePlayer()
activePlayer?.play()
}
}
在上面的示例中,我们创建了两个AVAudioPlayer对象,在循环播放时交替使用。在每次播放之后,我们检查活动播放器是否需要切换,以保持无缝循环的效果。