【问题标题】:AVAudioEngine throws exception when connecting AVAudioPlayerNode to output连接 AVAudioPlayerNode 到输出时 AVAudioEngine 抛出异常
【发布时间】:2017-11-29 04:33:34
【问题描述】:

我想做的(现在)就是使用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 的方法中。此方法在源自我的子类SKScene(称为GameScene)的触摸事件过程中被调用。在touchesBegan 上,调用将委托给所有具有TouchComponent 且具有相同签名(touchesBegan) 的方法的实体。这些组件将向它们的委托触发一个touchDown 事件,这又是我的GKStateMachine 的子类,称为GameStateMachine。如果触摸事件 正确 w.r.t.游戏规则,我的GameStateMachinescore 属性递增。在score 设置器中,如果分数增加,则调用最终方法playSound。这是我刚刚描述的序列图:

【问题讨论】:

  • 你是如何运行这段代码的?它是游乐场,iOS 应用程序的一部分,是视图控制器中的代码吗?您能否提供更多背景信息?因为在您尝试使用某些东西之前,它似乎被释放了。

标签: ios swift avfoundation avaudioplayer avaudioengine


【解决方案1】:

这是一个在 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 模拟器。请参阅我编辑的答案以获取更多信息。
【解决方案2】:

显然,抛出的异常是正常。它发生在我测试过的任何条件和任何环境中,但不会干扰正常功能。

没有播放声音的原因是AVAudioEngineAVAudioPlayerNode 对象在函数返回后立即被释放,因为它们没有强指针来保持它们活着。我已通过将这两个对象保留为 properties 来解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 2013-05-24
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多