Swift: Load a Wav sound using AVFoundation
I sometimes need to dynamically load a .wav file. Here's how I do it using AVFoundation.
func changeSound(_ song:(path: String, format: String)){
var err:NSError?
let track = Bundle.main.path(forResource: song.path, ofType: song.format)!
let u = URL(fileURLWithPath: track)
do {
audioPlayer = try AVAudioPlayer(contentsOf: u)
} catch let error as NSError {
err = error
audioPlayer = nil
}
if let error = err {
print("audioPlayer Err: \(error.localizedDescription)")
} else {
audioPlayer?.prepareToPlay()
}
if let player = audioPlayer {
player.play()
}
}