Guest User

Untitled

a guest
Apr 22nd, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. import UIKit
  2. import AVFoundation
  3.  
  4. class ViewController: UIViewController {
  5.  
  6. let engine = AVAudioEngine()
  7. let audioPlayer = AVAudioPlayerNode()
  8. let pitchUnit = AVAudioUnitTimePitch()
  9.  
  10. var avAudioFile: AVAudioFile!
  11.  
  12. override func viewDidLoad() {
  13. super.viewDidLoad()
  14. // Do any additional setup after loading the view, typically from a nib.
  15.  
  16. let path = Bundle.main.path(forResource: "Beep", ofType: "wav")!
  17. let url = NSURL.init(fileURLWithPath: path)
  18. avAudioFile = try? AVAudioFile(forReading: url as URL)
  19.  
  20. setup()
  21. }
  22.  
  23. func setup() {
  24. engine.attach(audioPlayer)
  25. engine.attach(pitchUnit)
  26. engine.connect(audioPlayer, to: pitchUnit, format: nil)
  27. engine.connect(pitchUnit, to:engine.mainMixerNode, format: nil)
  28.  
  29. try? engine.start()
  30.  
  31. audioPlayer.volume = 1.0
  32. audioPlayer.play()
  33.  
  34. }
  35. @IBAction func playSound(_ sender: UIButton) {
  36.  
  37. pitchUnit.pitch = 1
  38.  
  39. // interrupt playing sound if you have to
  40. if audioPlayer.isPlaying {
  41. audioPlayer.stop()
  42. audioPlayer.play()
  43. }
  44. let buffer = AVAudioPCMBuffer(pcmFormat: avAudioFile.processingFormat, frameCapacity: AVAudioFrameCount(avAudioFile.length))
  45. try? avAudioFile.read(into: buffer!)
  46. audioPlayer.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)
  47. }
  48.  
  49. @IBAction func stopSound(_ sender: UIButton) {
  50. audioPlayer.stop()
  51. }
  52. }
Add Comment
Please, Sign In to add comment