ios - AVAudioEngine 在连接 AVAudioPlayerNode 输出时抛出异常

标签 ios swift avfoundation avaudioplayer avaudioengine

我(现在)想做的就是使用 AVAudioEngineAVAudioPlayerNode 播放声音文件。这是我的代码:

//Init engine and player
let audioEngine = AVAudioEngine()
let audioPlayerNode = AVAudioPlayerNode()

//Hook them up
audioEngine.attach(audioPlayerNode)
audioEngine.connect(audioPlayerNode, to: audioEngine.outputNode, format: nil) // < error

执行最后一行时,抛出异常。没有任何内容打印到控制台并且执行继续,但是当我设置一个异常断点时,我得到以下 LLDB :

(lldb) po [$arg1 reason]
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0xffffd593).
The process has been returned to the state before expression evaluation.

这里不能访问什么?我什至还没有加载文件...感谢任何提示。

环境

  • Xcode 8.2.1
  • 运行 iOS 10.3.2 (14F89) 的 iPhone 5

编辑

这里是一些更多的上下文信息。上面的代码是使用 SpriteKitGameplayKit 构建的 iOS 游戏的一部分。它位于 GKStateMachine 的子类中,位于名为 playSound 的方法中。在源 self 的子类 SKScene(称为 GameScene)的触摸事件过程中调用此方法。在 touchesBegan 上,调用被委托(delegate)给所有具有 TouchComponent 的实体,这些实体的方法具有相同的签名 (touchesBegan)。这些组件将向它们的委托(delegate)触发一个 touchDown 事件,而委托(delegate)又是我的 GKStateMachine 子类,称为 GameStateMachine。如果触摸事件正确 w.r.t.游戏规则,我的 GameStateMachinescore 属性递增。在 score setter 中,如果分数增加,则调用 final方法 playSound。这是我刚才描述的序列图:

Sequence Diagram showing how "playSound" is invoked

最佳答案

这是一个在 playground 中播放本地文件资源的工作示例:

import AVFoundation
import PlaygroundSupport

// prevent program from exiting immediately
PlaygroundPage.current.needsIndefiniteExecution = true

let fileURL = Bundle.main.url(forResource: "song", withExtension: "mp3")!
let file = try! AVAudioFile(forReading: fileURL)

let audioEngine = AVAudioEngine()
let audioPlayerNode = AVAudioPlayerNode()

audioEngine.attach(audioPlayerNode)
audioEngine.connect(audioPlayerNode, to: audioEngine.outputNode, format: nil)

audioPlayerNode.scheduleFile(file, at: nil, completionHandler: nil)

// need to start the engine before we play
try! audioEngine.start()

audioPlayerNode.play()

这假设 song.mp3 存在于 playground 资源目录中。

关于ios - AVAudioEngine 在连接 AVAudioPlayerNode 输出时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44757962/

相关文章:

ios - 使用 iOS 库时 Storyboard View 未连接

ios - 如何检查两个 NSDate 之间的时间量?

ios - 如何在 Swift 中更改具有多个组件的 UIPickerView 的文本颜色?

ruby-on-rails - 使用来自 Facebook 的 Access_token 进行 Rails 身份验证

ios - iPhone 4 一个 iPhone 应用程序可以占用多少内存

swift - 检测具有 n 边的多边形的自相交?

iphone - 从 captureStillImageAsynchronouslyFromConnection 拍摄高分辨率照片

ios - AVFoundation 相机预览层不工作

ios - 快速录音和桌面 View 显示

ios - 如何在递归算法中保护 IOS 免受 EXC_BAD_ACCESS