Created
March 13, 2019 19:08
-
-
Save fatihyildizhan/699e9660895f3585e3f9355f5e5b627b to your computer and use it in GitHub Desktop.
Swift Sound Player
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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