我的代码有一个小问题,即在启动应用程序时播放声音。但是,每次我返回第一个屏幕时,都会出现问题,声音会再次播放,而我希望它只播放一次。当菜单屏幕第一次弹出时。
这是我的代码
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
}
最佳答案
您可以像这样定义一个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
如果需要的话再次播放声音。
关于xcode - 如何仅播放一次声音 SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35318652/