Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- import AVFoundation
- class ViewController: UIViewController {
- let engine = AVAudioEngine()
- let audioPlayer = AVAudioPlayerNode()
- let pitchUnit = AVAudioUnitTimePitch()
- var avAudioFile: AVAudioFile!
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view, typically from a nib.
- let path = Bundle.main.path(forResource: "Beep", ofType: "wav")!
- let url = NSURL.init(fileURLWithPath: path)
- avAudioFile = try? AVAudioFile(forReading: url as URL)
- setup()
- }
- func setup() {
- engine.attach(audioPlayer)
- engine.attach(pitchUnit)
- engine.connect(audioPlayer, to: pitchUnit, format: nil)
- engine.connect(pitchUnit, to:engine.mainMixerNode, format: nil)
- try? engine.start()
- audioPlayer.volume = 1.0
- audioPlayer.play()
- }
- @IBAction func playSound(_ sender: UIButton) {
- pitchUnit.pitch = 1
- // interrupt playing sound if you have to
- if audioPlayer.isPlaying {
- audioPlayer.stop()
- audioPlayer.play()
- }
- let buffer = AVAudioPCMBuffer(pcmFormat: avAudioFile.processingFormat, frameCapacity: AVAudioFrameCount(avAudioFile.length))
- try? avAudioFile.read(into: buffer!)
- audioPlayer.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)
- }
- @IBAction func stopSound(_ sender: UIButton) {
- audioPlayer.stop()
- }
- }
Add Comment
Please, Sign In to add comment