Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Apple's new AudioEngine to change Pitch of AudioPlayer sound

I am currently trying to get Apple's new audio engine working with my current audio setup. Specifically, I am trying to change the pitch with Audio Engine, which apparently is possible according to this post.

I have also looked into other pitch changing solutions including Dirac and ObjectAL, but unfortunately both seem to be pretty messed up in terms of working with Swift, which I am using.

My question is how do I change the pitch of an audio file using Apple's new audio engine. I am able to play sounds using AVAudioPlayer, but I am not getting how the file is referenced in audioEngine. In the code on the linked page there is a 'format' that refers to audio file, but I am not getting how to create a format, or what it does.

I am playing sounds with this simple code:

let path = NSBundle.mainBundle().pathForResource(String(randomNumber), ofType:"m4r")
let fileURL = NSURL(fileURLWithPath: path!)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.play()
like image 999
jake Avatar asked Sep 06 '14 21:09

jake


1 Answers

You use an AVAudioPlayerNode, not an AVAudioPlayer.

engine = AVAudioEngine()
playerNode = AVAudioPlayerNode()
engine.attachNode(playerNode)

Then you can attach an AVAudioUnitTimePitch.

var mixer = engine.mainMixerNode;
auTimePitch = AVAudioUnitTimePitch()
auTimePitch.pitch = 1200 // In cents. The default value is 1.0. The range of values is -2400 to 2400
auTimePitch.rate = 2 //The default value is 1.0. The range of supported values is 1/32 to 32.0.
engine.attachNode(auTimePitch)
engine.connect(playerNode, to: auTimePitch, format: mixer.outputFormatForBus(0))
engine.connect(auTimePitch, to: mixer, format: mixer.outputFormatForBus(0))
like image 131
Gene De Lisa Avatar answered Sep 28 '22 13:09

Gene De Lisa