Created
October 8, 2017 09:52
-
-
Save iAmrSalman/c29306b87493ad2b304c7879933edd21 to your computer and use it in GitHub Desktop.
[play audio] #swift4 #avfoundation
This file contains hidden or 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() { | |
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