使用AVAudioEngine离线渲染音频文件

5

我想录制音频文件并应用一些效果来保存它。 录制和播放带有效果的音频都没问题。 问题是当我尝试离线保存这样的音频时,会产生空的音频文件。 以下是我的代码:

let effect = AVAudioUnitTimePitch()
effect.pitch = -300
self.addSomeEffect(effect)

func addSomeEffect(_ effect: AVAudioUnit) {
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)

    let format = self.audioFile.processingFormat
    self.audioEngine.stop()
    self.audioEngine.reset()

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


    self.audioEngine.attach(audioPlayerNode)
    self.audioEngine.attach(effect)

    self.audioEngine.connect(audioPlayerNode, to: self.audioEngine.mainMixerNode, format: format)
    self.audioEngine.connect(effect, to: self.audioEngine.mainMixerNode, format: format)

    audioPlayerNode.scheduleFile(self.audioFile, at: nil)
    do {
        let maxNumberOfFrames: AVAudioFrameCount = 8096
        try self.audioEngine.enableManualRenderingMode(.offline,
                                                       format: format,
                                                       maximumFrameCount: maxNumberOfFrames)
    } catch {
        fatalError()
    }


    do {
        try audioEngine.start()
        audioPlayerNode.play()
    } catch {

    }

    let outputFile: AVAudioFile
    do {
        let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("temp.m4a")
        if FileManager.default.fileExists(atPath: url.path) {
            try? FileManager.default.removeItem(at: url)
        }

        let recordSettings = self.audioFile.fileFormat.settings

        outputFile = try AVAudioFile(forWriting: url, settings: recordSettings)
    } catch {
        fatalError()
    }

    let buffer = AVAudioPCMBuffer(pcmFormat: self.audioEngine.manualRenderingFormat,
                                  frameCapacity: self.audioEngine.manualRenderingMaximumFrameCount)!

    while self.audioEngine.manualRenderingSampleTime < self.audioFile.length {
        do {
            let framesToRender = min(buffer.frameCapacity,
                                     AVAudioFrameCount(self.audioFile.length - self.audioEngine.manualRenderingSampleTime))
            let status = try self.audioEngine.renderOffline(framesToRender, to: buffer)
            switch status {
            case .success:
                print("Write to file")
                try outputFile.write(from: buffer)
            case .error:
                fatalError()
            default:
                break
            }
        } catch {
            fatalError()
        }
    }
    print("Finish write")


    audioPlayerNode.stop()
    audioEngine.stop()


    self.outputFile = outputFile
    self.audioPlayer = try? AVAudioPlayer(contentsOf: outputFile.url)

}

AVAudioPlayer无法打开具有输出URL的文件。我通过文件系统查看了该文件,它是空的,不能播放。

为AVAudioSession选择不同的类别也没有起作用。

感谢您的帮助!

更新

我在记录输出文件时切换到使用.caf文件扩展名,它奏效了。任何关于为什么.m4a无法工作的想法吗?


1
你需要将outputFile设为nil,以刷新头文件并关闭m4a文件。 - Rhythmic Fistman
@RhythmicFistman 谢谢,它有效! - Mikita Kaltsou
1个回答

7
你需要将outputFile置为nil,以刷新头部并关闭m4a文件。

抱歉,只是为了明确,您的意思是在所有内容完成渲染后的某个时刻将outputFile设置为nil吗? - AdjunctProfessorFalcon
没错。在你写完最后一个缓冲区后,通常会调用close,但现在你要将AVAudioFile设置为nil。 - Rhythmic Fistman
6
在我看来,这是一个极其愚蠢的API决定。利用对象清理的副作用来关闭文件既不容易发现,也是不确定的。我不明白为什么AVAudioFile没有一个显式的close()方法。 - Rob Keniger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接