我正在尝试使用新的 AVAudioSourceNode
运行一个简单的振荡器Apple 在最新版本中推出。代码摘自 Apple 发布的示例代码 available here .
但是,每当我在 Swift 操场上运行它时,都会触发回调,但不会发出任何声音。当我将此代码移动到 iOS 应用程序时,它工作正常。知道发生了什么吗? AFAIK 其他音频节点在 Playgrounds 中运行良好,所以我不确定为什么这个特定的节点会失败。请参阅下面的代码。使用 Xcode 11 和 macOS 10.15 运行。
import AVFoundation
import PlaygroundSupport
let audioEngine = AVAudioEngine()
let mainMixerNode = audioEngine.mainMixerNode
let outputNode = audioEngine.outputNode
let format = outputNode.inputFormat(forBus: 0)
let incrementAmount = 1.0 / Float(format.sampleRate)
var time: Float = 0.0
func sineWave(time: Float) -> Float {
return sin(2.0 * Float.pi * 440.0 * time)
}
let sourceNode = AVAudioSourceNode { (_, _, frameCount, audioBufferList) -> OSStatus in
let bufferListPointer = UnsafeMutableAudioBufferListPointer(audioBufferList)
for frameIndex in 0..<Int(frameCount) {
let sample = sineWave(time: time)
time += incrementAmount
for buffer in bufferListPointer {
let buf: UnsafeMutableBufferPointer<Float> = UnsafeMutableBufferPointer(buffer)
buf[frameIndex] = sample
}
}
return noErr
}
audioEngine.attach(sourceNode)
audioEngine.connect(sourceNode, to: mainMixerNode, format: format)
audioEngine.connect(mainMixerNode, to: outputNode, format: nil)
mainMixerNode.outputVolume = 0.5
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print(error.localizedDescription)
}
PlaygroundPage.current.needsIndefiniteExecution = true
最佳答案
看来 Playground 打印真的破坏了实时处理 block 的性能。我遇到了同样的问题,然后按照建议将 AVAudioSourceNode 代码移动到 Sources 文件夹中的另一个 .swift 文件中 here
关于swift - AVAudioSourceNode 在快速 Playground 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58604939/