Playing system sounds using Swift

user3353890 picture user3353890 · Oct 27, 2014 · Viewed 6.9k times · Source

I'm trying to play a sound when a button is pressed using system sounds. I keep getting the error: "fatal error: unexpectedly found nil while unwrapping an Optional value". I tried debugging, and I believe the error is occurring on the var ref line. "roar.aif" is a custom sound I have included in my project. It is only a second and a half long. I would appreciate suggestions. Thanks!

        var soundID: SystemSoundID = SystemSoundID()
        var mainBundle: CFBundleRef = CFBundleGetMainBundle()
        var ref: CFURLRef = CFBundleCopyResourceURL(mainBundle, "roar.aif", nil, nil) as CFURLRef!
        println("Here is your ref: \(ref)")
        AudioServicesCreateSystemSoundID(ref, &soundID)
        AudioServicesPlaySystemSound(soundID)

Answer

Tom picture Tom · Oct 27, 2014

I believe the correct way is to use the filetype in the third parameter:

    var soundID: SystemSoundID = 0
    var mainBundle: CFBundleRef = CFBundleGetMainBundle()
    if let ref: CFURLRef = CFBundleCopyResourceURL(mainBundle, CFSTR("roar"), CFSTR("aif"), nil) {
        println("Here is your ref: \(ref)")
        AudioServicesCreateSystemSoundID(ref, &soundID)
        AudioServicesPlaySystemSound(soundID)
    } else {
        println("Could not find sound file")
    }

Are you sure the file is roar.aif and not roar.aiff?

Make sure the file is not in a subdirectory, if so you have to add this as a fourth parameter.

See: https://developer.apple.com/library/mac/documentation/CoreFoundation/Reference/CFBundleRef/index.html#//apple_ref/c/func/CFBundleCopyResourceURL