Skip to content

Instantly share code, notes, and snippets.

@joshdance
Last active March 22, 2018 05:26
Show Gist options
  • Save joshdance/1dfd1ac954bcb61ce16f60937785e8ad to your computer and use it in GitHub Desktop.
Save joshdance/1dfd1ac954bcb61ce16f60937785e8ad to your computer and use it in GitHub Desktop.
Simple example of how to play sounds Swift 4
class ViewController {
var audioPlayer = AVAudioPlayer()
struct Sounds {
static let startupSound: String = "soundname1.wav"
static let downSound: String = "soundname4.mp3"
static let upSound: String = "soundname3.aif"
static let saveSound: String = "soundname2.wav"
}
override func viewDidLoad() {
super.viewDidLoad()
playSound(sound: Sounds.startupSound)
}
func playSound(sound: String){
let path = Bundle.main.path(forResource: sound, ofType: nil)!
let url = URL(fileURLWithPath: path)
do {
audioPlayer = try AVAudioPlayer(contentsOf: url)
audioPlayer.play()
} catch {
print("couldn't load the file")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment