Reputation: 79
How do we use rate in AVAudioEngine?
Here's my complete code:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioEngine = AVAudioEngine()
var myPlayer = AVAudioPlayerNode()
override func viewDidLoad() {
super.viewDidLoad()
if var filePath = NSBundle.mainBundle().pathForResource("music", ofType: "wav"){
var filePathURL = NSURL.fileURLWithPath(filePath)
audioEngine.attachNode(myPlayer)
var audioFile = AVAudioFile(forReading: filePathURL, error: nil)
var audioError:NSError?
audioEngine.connect(myPlayer, to: audioEngine.mainMixerNode, format: audioFile.processingFormat)
myPlayer.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(&audioError)
}else {
println("url not found")
}
}
@IBAction func playSound(sender: UIButton) {
myPlayer.rate = 0.5
myPlayer.play()
}
So while I play the sound its not using the rate at at all. Furthermore, how do I reset the position once I am done playing the audio. AVAudioPlayer had currentTime to use to reset the bar.
Edit1: This is rather confusing cause if AVAudioPlayerNode doesn't have a class to maintain why does it allow me to use rate at all? Sorry completely noob to programming.
Edit2: Got it working with help from Matt's example code. I missed the audio output line:
var audioEngine = AVAudioEngine()
var myPlayer = AVAudioPlayerNode()
audioEngine.attachNode(myPlayer)
var changeAudioUnitTime = AVAudioUnitTimePitch()
changeAudioUnitTime.rate = audioChangeNumber
audioEngine.attachNode(changeAudioUnitTime)
audioEngine.connect(myPlayer, to: changeAudioUnitTime, format: nil)
audioEngine.connect(changeAudioUnitTime, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)
audioPlayerNode.play()
Thanks everyone for the help.
Upvotes: 1
Views: 2185
Reputation: 534924
To change the rate with AVAudioEngine, you have two choices:
Do 3D mixing with an AVAudioEnvironmentNode. Only the AVAudioEnvironmentNode has a meaningful AVAudio3DMixing protocol rate
property.
Pass the file output through an AVAudioUnitTimePitch node and adjust its rate
.
Upvotes: 2