无延迟播放音效

Play sound effect without latency

我正在尝试制作一个小应用程序来自学一些东西 swift,但我在弄清楚如何让我的应用程序以某种方式运行时遇到了一些问题。

我的应用程序应该能够播放气喇叭的声音,就像它在这个视频中的声音一样...

https://www.youtube.com/watch?v=Ks5bzvT-D6I

但是每次我反复点击屏幕时,在播放声音之前都会有轻微的延迟,所以听起来根本不像那样。

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        var hornSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("horn", ofType: "mp3")!)

        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: hornSound, error: &error)
        audioPlayer.prepareToPlay()
    }

    @IBAction func playSound(sender: UIButton) {
        audioPlayer.pause()
        audioPlayer.currentTime = 0
        audioPlayer.play()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

我也遇到过关于使用 spritekit 的帖子

Creating and playing a sound in swift

在尝试让它播放声音时没有延迟,但是使用 sprite 套件我无法停止现有的声音,所以它们只是重叠,这不是我想要的效果。

是否有变通办法使它按照视频中的声音运行。

Apple 建议 AVAudioPlayer 播放音频数据 ,除非您需要非常低的 I/O 延迟

所以你可能想尝试另一种方法。

在我的一个应用程序中,我通过从我的 wav 文件创建系统声音 ID 来播放倒计时声音。在您的 class:

中试试这个
import UIKit
import AudioToolbox

class ViewController: UIViewController {
    var sound: SystemSoundID = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        var hornSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("horn", ofType: "mp3")!)

        AudioServicesCreateSystemSoundID(hornSound!, &self.sound)
    }

    @IBAction func playSound(sender: UIButton) {
        AudioServicesPlaySystemSound(self.sound)
    }

    ...
}