如何只播放一次SWIFT声音

时间:2016-02-10 15:02:59

标签: xcode swift audio

我的代码有点问题,我在启动应用时发出声音。但是每次我回到第一个屏幕再次播放声音时我都会遇到这个问题,我希望它只播放一次。当菜单屏幕第一次弹出时。

这是我的代码

   var bubbleSound: SystemSoundID!
 bubbleSound = createBubbleSound()
 AudioServicesPlaySystemSound(bubbleSound)

(...)

功能

func createBubbleSound() -> SystemSoundID {
            var soundID: SystemSoundID = 0
    let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "bubble", "wav", nil)
    AudioServicesCreateSystemSoundID(soundURL, &soundID)
    return soundID

}

1 个答案:

答案 0 :(得分:0)

您可以定义struct这样的source):

struct MyViewState {
    static var hasPlayedSound = false
}

然后在viewDidLoad

if(!MyViewState.hasPlayedSound) {
    var bubbleSound: SystemSoundID!
    bubbleSound = createBubbleSound()
    AudioServicesPlaySystemSound(bubbleSound)
    MyViewState.hasPlayedSound = true
}

然后,您可以修改MyViewState.hasPlayedSound并允许UIViewController根据需要再次播放声音。