问题描述
我希望使用Xcode,Swift 4中的滑块或变量(即在播放声音时)实时更改某些音频的音调和播放速度.
I'm looking to change the pitch and playback speed of some audio in real time with a slider, or a variable (i.e. while the sound is playing) in Xcode, Swift 4.
当前,我正在使用AVAudioEngine,它允许我在播放开始之前设置这些值,但是在实际播放音频时无法更改它们.
Currently, I'm using AVAudioEngine, which allows me to set these values before playback starts, but I can't change them while I the audio is actually playing.
这是有问题的代码:
func Play() {
engine = AVAudioEngine()
audioPlayer = AVAudioPlayerNode()
audioPlayer.volume = 1.0
let path = Bundle.main.path(forResource: "filename", ofType: "mp3")!
let url = NSURL.fileURL(withPath: path)
let file = try? AVAudioFile(forReading: url)
let buffer = AVAudioPCMBuffer(pcmFormat: file!.processingFormat, frameCapacity: AVAudioFrameCount(file!.length))
do {
try file!.read(into: buffer!)
} catch _ {
}
let pitch = AVAudioUnitTimePitch()
let speed = AVAudioUnitVarispeed()
pitch.pitch = speedIncrement * (-500)
speed.rate = speedIncrement
engine.attach(audioPlayer)
engine.attach(pitch)
engine.attach(speed)
engine.connect(audioPlayer, to: speed, format: buffer?.format)
engine.connect(speed, to: pitch, format: buffer?.format)
engine.connect(pitch, to: engine.mainMixerNode, format: buffer?.format)
audioPlayer.scheduleBuffer(buffer!, at: nil, options: AVAudioPlayerNodeBufferOptions.loops, completionHandler: nil)
engine.prepare()
do {
try engine.start()
} catch _ {
}
audioPlayer.play()
}
使用AVAudioEngine甚至有可能吗?
Is this even possible with AVAudioEngine?
如果AVAudioEngine无法做到这一点,还有哪些其他可能的解决方案?
If this is not possible with AVAudioEngine, what are other possible solutions?
推荐答案
实际上,我从reddit那里得到了答案.我要做的就是在Play()
函数之外声明pitch
和speed
变量,以及pitch.pitch = speedIncrement * (-500)
和speed.rate = speedIncrement
表达式.我知道我缺少一些简单的东西...
Actually, I got the answer from reddit. All I had to do was to declare the pitch
and speed
variables outside of the Play()
function, along with the pitch.pitch = speedIncrement * (-500)
and speed.rate = speedIncrement
expressions. I knew I was missing something simple...
这篇关于播放期间如何更改音高? (快速4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!