xcode - 如何仅播放一次声音 SWIFT

标签 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

}

最佳答案

您可以像这样定义一个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/

相关文章:

ios - Xcode 机器人服务器持续集成失败

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

javascript - soundcloud api和web音频api不能一起使用

android - 哪种AudioEncoder编解码器最适合Android上最高质量的音频录制

xcode - 使用 Interface Builder 在 nib 中设计 UICollectionView 单元格(没有 Storyboard )

ios - MyClass 不可用 : cannot find Swift declaration for this class

ios - TableViewController 中各部分上方的 Xcode 文本字段

swift 3 : UIButton re-enables after midnight

ios - 如何删除用户移动手指的 UIImage 区域?

javascript - 音频与onmousedown一起在Javascript/CSS中切出过早