在 AVAudioPlayer 中播放音调时如何在循环之间添加延迟?

How to add a delay between loops when playing a tone in AVAudioPlayer?

我创建了一个示例函数,它会无限循环地立即播放一段短音。这是代码:

let audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.numberOfLoops = -1
audioPlayer.play()

如何在播放器再次播放音调之前创建 5 秒延迟?有办法吗?

不幸的是,没有简单的方法可以做到这一点。你应该使用 AVAudioPlayerDelegate。请在下面找到一些示例:

class ViewController: UIViewController, AVAudioPlayerDelegate
{
    private var player: AVAudioPlayer!

    @objc private func startPlaying()
    {
         self.player = try? AVAudioPlayer(contentsOf: url)
         self.player.delegate = self
         self.player.play()
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool)
    {
         self.perform(#selector(startPlaying), with: nil, afterDelay: 5)
    }
}

不要忘记在您想停止继续播放音频时停止选择器:

NSObject.cancelPreviousPerformRequests(withTarget: self)