将 AVAudioPlayer 声音保存在内存中

Keep AVAudioPlayer sound in the memory

我使用 AVAudioPlayer 在用户点击按钮时播放点击声音。

因为点击和声音之间存在延迟,所以我在 viewDidAppear 中播放了一次声音,音量 = 0

我发现,如果用户在一段时间内点击按钮,声音会立即播放,但在这种情况下,过了一定时间后,点击和声音之间也会有延迟。

好像第一种情况声音来自初始播放的缓存,第二种情况应用程序必须重新加载声音。

因此,现在我每 2 秒播放一次声音,音量为 0,当用户实际点击按钮时,声音会立即出现。

我的问题是有更好的方法吗?

我的目标是在应用程序的整个生命周期内将声音保存在缓存中。

谢谢,

如果您保存指向 AVAudioPlayer 的指针,那么您的声音将保留在内存中并且不会发生其他延迟。 第一次延迟是由声音加载引起的,所以你在 viewDidAppear 中的第一次播放是正确的。

为避免音频延迟,请使用 AVAudioPlayer 的 .prepareToPlay() 方法。

Apple's Documentation on Prepare To Play

Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play() method and the start of sound output.

如果 player 被声明为 AVAudioPlayer 则可以调用 player.prepareToPlay() 来避免音频延迟。示例代码:

struct AudioPlayerManager {

    var player: AVAudioPlayer? = AVAudioPlayer()

    mutating func setupPlayer(soundName: String, soundType: SoundType) {

    if let soundURL = Bundle.main.url(forResource: soundName, withExtension: soundType.rawValue) {
        do {
            player = try AVAudioPlayer(contentsOf: soundURL)
            player?.prepareToPlay()
        }
        catch  {
            print(error.localizedDescription)
        }
    } else {
        print("Sound file was missing, name is misspelled or wrong case.")
    }
}

然后可以以最小的延迟调用 play():

player?.play()