-50 error when converting PCM buffer with AVAudioConverter

I'm trying to convert a AVAudioPCMBuffer with a 44100 sample rate to one with a 48000 sample rate, but I always get an exception (-50 error) when converting. Here's the code:


        guard let deviceFormat = AVAudioFormat(standardFormatWithSampleRate: 48000.0, channels: 1) else {
            preconditionFailure()
        }

        // This file is saved as mono 44100
        guard let lowToneURL = Bundle.main.url(forResource: "Tone220", withExtension: "wav") else {
            preconditionFailure()
        }
        guard let audioFile = try? AVAudioFile(forReading: lowToneURL) else {
            preconditionFailure()
        }

        let tempBuffer = AVAudioPCMBuffer(pcmFormat: audioFile.processingFormat,
                                       frameCapacity: AVAudioFrameCount(audioFile.length))!
        tempBuffer.frameLength = tempBuffer.frameCapacity
        do { try audioFile.read(into: tempBuffer) } catch {
            assertionFailure("*** Caught: \(error)")
        }

        guard let converter = AVAudioConverter(from: audioFile.processingFormat, to: deviceFormat) else {
            preconditionFailure()
        }
        guard let convertedBuffer = AVAudioPCMBuffer(pcmFormat: deviceFormat,
                                                     frameCapacity: AVAudioFrameCount(audioFile.length)) else {
            preconditionFailure()
        }
        convertedBuffer.frameLength = tempBuffer.frameCapacity
        do { try converter.convert(to: convertedBuffer, from: tempBuffer) } catch {
            assertionFailure("*** Caught: \(error)")
        }


Any ideas?

Accepted Reply

Actually, the answer is in the documentation for convert(to:from:) [https://developer.apple.com/documentation/avfoundation/avaudioconverter/1388341-convert]:


Performs a simple conversion that doesn't involve codecs or sample rate conversion.


Error - 50 indicates an invalid parameter, and that's because you are changing the sample rate. Instead, use convert(to:error:withInputFrom:) [https://developer.apple.com/documentation/avfoundation/avaudioconverter/1387865-convert].

Replies

Actually, the answer is in the documentation for convert(to:from:) [https://developer.apple.com/documentation/avfoundation/avaudioconverter/1388341-convert]:


Performs a simple conversion that doesn't involve codecs or sample rate conversion.


Error - 50 indicates an invalid parameter, and that's because you are changing the sample rate. Instead, use convert(to:error:withInputFrom:) [https://developer.apple.com/documentation/avfoundation/avaudioconverter/1387865-convert].

Thanks. I missed the "doesn't involve … sample rate" part of the docs and it wasn't clear to me how the other `convert` variant was supposed to work. But it's working now.