Skip to content

Instantly share code, notes, and snippets.

@MichaelSDavid
Created July 5, 2022 23:13
Show Gist options
  • Save MichaelSDavid/d9f22c65e8916662182dc5b409e92110 to your computer and use it in GitHub Desktop.
Save MichaelSDavid/d9f22c65e8916662182dc5b409e92110 to your computer and use it in GitHub Desktop.
Plays a sound file in Swift for usage in iOS/Mac apps with something like a button or gesture trigger.
import AVFoundation
var player: AVAudioPlayer?
func playSound(name: String) {
// Change extension as needed
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment