Skip to content

Instantly share code, notes, and snippets.

@iAmrSalman
Created October 8, 2017 09:52
Show Gist options
  • Save iAmrSalman/c29306b87493ad2b304c7879933edd21 to your computer and use it in GitHub Desktop.
Save iAmrSalman/c29306b87493ad2b304c7879933edd21 to your computer and use it in GitHub Desktop.
[play audio] #swift4 #avfoundation
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
/// Make sure to change the name of your tune as well as the extension. The file needs to be properly imported `Project Build Phases > Copy Bundle Resources`. You might want to place it in `assets.xcassets` for greater convenience.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment