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

大兔子大兔子 提交于 2019-12-03 05:13:30

问题


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()

回答1:


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))


来源:https://stackoverflow.com/questions/25704923/using-apples-new-audioengine-to-change-pitch-of-audioplayer-sound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!