Reputation: 1235
I'm trying to change the pitch of a sound using the AVAudioEngine()
in Swift. This is my code:
func setUpEngine() {
let fileString = NSBundle.mainBundle().pathForResource("400", ofType: "wav")
let url = NSURL(fileURLWithPath: fileString!)
do {
try audioFile = AVAudioFile(forReading: url)
print("done")
}
catch{
}
}
var engine = AVAudioEngine()
var audioFile = AVAudioFile()
var audioPlayerNode = AVAudioPlayerNode()
var changeAudioUnitTime = AVAudioUnitTimePitch()
override func viewDidLoad() {
setUpEngine()
let defaults = NSUserDefaults.standardUserDefaults()
audioPlayerNode.stop()
engine.stop()
engine.reset()
engine.attachNode(audioPlayerNode)
changeAudioUnitTime.pitch = 800
engine.attachNode(changeAudioUnitTime)
engine.connect(audioPlayerNode, to: changeAudioUnitTime, format: nil)
engine.connect(changeAudioUnitTime, to: engine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
engine.startAndReturnError(nil)
audioPlayerNode.play()
The rest of my code is below (I do close the brackets). I found most of this code online and I get an error with the line
engine.startAndReturnError(nil)
'Value of type has no member'.
When I remove this line I get the following error:
'AVAudioPlayerNode.mm:333: Start: required condition is false: _engine->IsRunning() Terminating app due to uncaught exception 'com.apple.coreaudio.avfaudio', reason: 'required condition is false: _engine->IsRunning()''
Any help would be greatly appreciated. I am using Swift in xCode and a single view application.
Upvotes: 3
Views: 4919
Reputation: 942
The error is that the engine is not running. You need to reorder your operations like this...
setUpEngine()
let defaults = NSUserDefaults.standardUserDefaults()
engine.attachNode(audioPlayerNode)
engine.attachNode(changeAudioUnitTime)
engine.connect(audioPlayerNode, to: changeAudioUnitTime, format: nil)
engine.connect(changeAudioUnitTime, to: engine.outputNode, format: nil)
changeAudioUnitTime.pitch = 800
engine.prepare()
engine.start()
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioPlayerNode.play()
Some time later...
engine.stop()
Upvotes: 4
Reputation: 162
This is because you are running on either outdated version of XCode or incompatible version of iOS. I had this issue and in the latest Swift version there is no such method instead they provide .start().
Upvotes: 0