如何从同一个AVAudioEngine播放多个不同的音频文件? (错误:!nodeimpl-> HasEngineImpl())

时间:2017-09-06 00:06:58

标签: ios swift audio avaudioengine avaudiofile

在我的应用程序中,每次按下表格视图中的不同单元格时,我都想播放不同的音频文件。下面是我的实现,但我一直收到错误:

  

因未捕获的异常'com.apple.coreaudio.avfaudio'而终止应用程序,原因:'必需条件为false:!nodeimpl-> HasEngineImpl()'

我认为此错误意味着它正在崩溃,因为音频引擎已经包含节点。但我不知道如何解决这个问题。

var audioPlayerFile : AVAudioFile!
var audioEngine = AVAudioEngine()
var pitchPlayer = AVAudioPlayerNode()
var timePitch = AVAudioUnitTimePitch()
var delay = AVAudioUnitDelay()

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        pitchPlayer.stop()
        audioEngine.stop()
        audioEngine.reset()

    let filePathResource = myConversation.conversation[indexPath.row].fileName

    print("file:", filePathResource)
    if (filePathResource != nil) {
        setUpAudioFilePath(filePathRes: filePathResource!)
    }

    timePitch.pitch = 0
    delay.delayTime = 0

    //append more effect:
    audioEngine.connect(pitchPlayer, to: timePitch, format: audioPlayerFile.processingFormat)
    audioEngine.connect(timePitch, to: delay, format: audioPlayerFile.processingFormat)
    audioEngine.connect(delay, to: audioEngine.outputNode, format: audioPlayerFile.processingFormat)

    pitchPlayer.scheduleFile(audioPlayerFile, at: nil, completionHandler: nil)
    do { try audioEngine.start()}
    catch {
        print("Error: Starting Audio Engine")
    }

    pitchPlayer.play()

}

func setUpAudioFilePath (filePathRes: String) {

    if let filePath = Bundle.main.path(forResource: filePathRes, ofType: "m4a") {

        let filePathUrl = NSURL.fileURL(withPath: filePath)
        do { audioPlayerFile = try AVAudioFile(forReading: filePathUrl) }
        catch {
            print("Error: Reading Audio Player File")
        }
        audioEngine.attach(pitchPlayer)
        audioEngine.attach(timePitch)
        audioEngine.attach(delay)

    } else {
        print("Error: filePath is empty")
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你需要混音器来播放多个音频。 AVAudioEngine已经有了与outputNode连接的混音器。 试试这个

audioEngine.connect(pitchPlayer, to: timePitch, format: audioPlayerFile.processingFormat)
audioEngine.connect(timePitch, to: delay, format: audioPlayerFile.processingFormat)
audioEngine.connect(delay, to: audioEngine.mainMixerNode, format: audioPlayerFile.processingFormat)