无延迟播放音效

3
我正在尝试制作一个小应用程序,以自学一些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的这个主题。尝试使用在Swift中创建和播放声音,我成功地播放了声音而没有延迟,但是在使用SpriteKit时,我无法停止现有的声音,所以它们只会重叠,这不是我想要的效果。是否有解决方法可以让它像视频中听起来那样工作?
1个回答

5

如果您不需要非常低的I/O延迟,苹果建议使用AVAudioPlayer来播放音频数据。

因此,您可能需要尝试另一种方法。

在我的一个应用程序中,我通过从wav文件创建系统声音ID来播放倒计时声音。请在您的类中尝试以下代码:

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)
    }

    ...
}

谢谢!我之前遇到过这个问题,但是第一次尝试时可能已经解决了。结果,事实证明我的音频文件一直有点延迟。-_- - Jordan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接