【问题标题】:Play sound effect without latency无延迟播放音效
【发布时间】:2015-10-25 21:20:55
【问题描述】:

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

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

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

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

是否有变通方法可以让其按照视频中的声音方式工作。

【问题讨论】:

    标签: ios swift audio avfoundation avaudioplayer


    【解决方案1】:

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

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

    在我的一个应用程序中,我通过从我的 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)
        }
    
        ...
    }
    

    【讨论】:

    • 谢谢!我以前遇到过这种情况,但事实证明这可能在我第一次尝试时就奏效了,结果我的音频文件在整个开始时都有一点延迟-_-
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多