Search code examples
iosavfoundationcore-audioaudiotoolbox

How to export 32 Bit WAV file with AVAssetWriter on iOS?


I try to export wav 32bit file, but AVAssetWriter can not add input

           let setting = [
                AVFormatIDKey : kAudioFormatLinearPCM,
                AVSampleRateKey : 44100,
                AVNumberOfChannelsKey : 2,
                AVLinearPCMBitDepthKey : 32,
                AVLinearPCMIsNonInterleaved : false,
                AVLinearPCMIsFloatKey : true,
                AVLinearPCMIsBigEndianKey : false,
            ]
            
            // 设置 reader & writer
            let reader = try! AVAssetReader(asset: composition)
            let readerOutput = AVAssetReaderAudioMixOutput(audioTracks: composition.tracks(withMediaType: .audio), audioSettings: nil)
            readerOutput.audioMix = mix
            reader.add(readerOutput)
            
            let writer = try! AVAssetWriter(outputURL: outputTempURL, fileType: .wav)
            let writerInput = AVAssetWriterInput(mediaType: .audio,
                                                 outputSettings: exportSetting)
            if writer.canAdd(writerInput) {
                writer.add(writerInput)
            } else {
                // will be here
                return
            }

So what can I to export 32 Bit WAV file


Solution

  • If you add the input without asking whether it's possible, you get a descriptive error logged to the console:

    *** -[AVAssetWriter addInput:] WAVE files cannot contain floating-point LPCM

    This statement about WAVE files doesn't seem to actually be true however AVAssetWriter believes it, so if you want a 32bit float wav file, you may have to try another API or library.

    If you're happy with 32bit integer samples, then set AVLinearPCMIsFloatKey to false.