Posted By

chrisaiv on 10/23/16


Tagged

iphone swift


Versions (?)

Swift: Load a Wav sound using AVFoundation


 / Published in: iPhone
 

I sometimes need to dynamically load a .wav file. Here's how I do it using AVFoundation

  1. func changeSound(_ song:(path: String, format: String)){
  2. var err:NSError?
  3. let track = Bundle.main.path(forResource: song.path, ofType: song.format)!
  4. let u = URL(fileURLWithPath: track)
  5. do {
  6. audioPlayer = try AVAudioPlayer(contentsOf: u)
  7. } catch let error as NSError {
  8. err = error
  9. audioPlayer = nil
  10. }
  11. if let error = err {
  12. print("audioPlayer Err: \(error.localizedDescription)")
  13. } else {
  14. audioPlayer?.prepareToPlay()
  15. }
  16. if let player = audioPlayer {
  17. player.play()
  18. }
  19.  
  20. }

Report this snippet  

You need to login to post a comment.