swift - AVAudioSourceNode 在快速 Playground 中不起作用

标签 swift audio swift-playground avaudioengine

我正在尝试使用新的 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/

相关文章:

ios - 使用千位分隔符格式化 Int64

macos - Mac 应用程序窗口停止更新

java - 从音频 PCM 16 位到 8 位 - 有噪音

Swift Playground - 如何将带逗号的字符串转换为带小数的字符串

ios - Xcode 7.1 中没有 "Run in Full Simulator"的 UIView 动画?

ios - 有没有办法在 iOS UI 测试自动化中使用坐标来选择元素?

ios - Swift:如何使用 SQLite 列填充 UITableView

audio - 如何解决 PJSIP 中接收音频 RTP 流(音质差)时的 Jitter Buffer 问题?

iphone - 打鼓应用程序 - 延迟声音......如何修复?

swift - 苹果操作系统 : Accessing contents directly from a directory in Swift