mainMixerNode 在 swift 中崩溃

mainMixerNode crash in swift

我正在尝试下面的代码,我正在使用这个示例 http://www.tmroyal.com/playing-sounds-in-swift-audioengine.html

此行时应用程序崩溃。

var mixer = engine.mainMixerNode

代码如下:

var buffer:AVAudioPCMBuffer
var sr:Float

let engine:AVAudioEngine = AVAudioEngine()
var player:AVAudioPlayerNode = AVAudioPlayerNode()

var mixer = engine.mainMixerNode

engine.attach(player)

engine.connect(player, to: mixer, format: player.outputFormat(forBus: 0))

buffer = AVAudioPCMBuffer(pcmFormat: player.outputFormat(forBus: 0), frameCapacity: 100)

buffer.frameLength = 100

sr = Float(mixer.outputFormat(forBus: 0).sampleRate)


var i:Int=0

while i < Int(buffer.frameLength) {
    var val = sinf(441.0*Float(i)*2*Float(M_PI) / Float(sr))
    buffer.floatChannelData?.pointee[i] = val * 0.5
    i+=1
}


try! engine.start()

player.play()

player.scheduleBuffer(buffer, at: nil, options: .loops, completionHandler: nil)

Swift3 中的 mainMixerNode 有什么变化吗?我该如何解决该崩溃问题?

我创建了一个新项目,并在新项目中尝试了这段代码。 现在可以了。