Created
July 5, 2022 23:13
-
-
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.
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 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