Playing sound in Swift using AVFoundation
// First import AVFoundation library
import AVFoundation
// Create audioPlayer
var audioPlayer: AVAudioPlayer!
// Create sound playing function
func playSound() {
// Url to sound file
let soundUrl = Bundle.main.url(forResource: "name", withExtension: "mp3")
do {
// Make player with sound file
audioPlayer = try AVAudioPlayer(contentsOf: soundUrl!)
} catch {
print(error)
}
// Play sound
audioPlayer.play()
}
/* NOTES */
// stop playing sound
audioPlayer.stop()
// pause playing sound
audioPlayer.pause()