Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fatihyildizhan/699e9660895f3585e3f9355f5e5b627b to your computer and use it in GitHub Desktop.
Save fatihyildizhan/699e9660895f3585e3f9355f5e5b627b to your computer and use it in GitHub Desktop.
Swift Sound Player
import UIKit
import AudioToolbox
struct SoundPlayer {
static var filename : String?
static var enabled : Bool = true
private struct Internal {
static var cache = [URL:SystemSoundID]()
}
static func playSound(soundFile: String) {
if !enabled {
return
}
if let url = Bundle.main.url(forResource: soundFile, withExtension: nil) {
var soundID : SystemSoundID = Internal.cache[url] ?? 0
if soundID == 0 {
AudioServicesCreateSystemSoundID(url as CFURL, &soundID)
Internal.cache[url] = soundID
}
AudioServicesPlaySystemSound(soundID)
} else {
print("Could not find sound file name `\(soundFile)`")
}
}
// call the function with filename
static func play(file: String) {
self.playSound(soundFile: file)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment