4

I'm using AVAudioEngine to record audio, and saving it as a sound file.

The user can choose to import an audio file, and they can then continue to record at the end of this file if they wish to. I'm getting the audio data from the imported file by reading it into an AVAudioPCMBuffer, which I then write to the file I'm recording to. This works great if the imported file is in stereo (since the file I'm writing to is also in stereo). But if the imported file is in mono, the code crashes when I'm trying to write the AVAudioPCMBuffer to the file, simply because the number of channels don't match.

Is it possible to read a mono AVAudioPCMBuffer into av AVAudioFile with a processingFormat set to stereo? Can I convert the buffer to stereo?

Here's an example of how I'm getting the audio buffer from the imported file:

let existingAudioFile = try AVAudioFile(forReading: existingFileUrl)
var audioFrameCount = AVAudioFrameCount(existingAudioFile.length)
let audioBuffer = AVAudioPCMBuffer(PCMFormat: existingAudioFile.processingFormat, frameCapacity: audioFrameCount) //Mono
try existingAudioFile.readIntoBuffer(audioBuffer)

And this is where I create the AVAudioFile I'm writing to using AVAudioEngine:

self.audioFile = try AVAudioFile(forWriting: self.audioRecordURL, settings: self.engine.mainMixerNode.outputFormatForBus(0).settings) //This is in stereo

And finally, this is how I write the audio buffer to the file:

try self.audioFile.writeFromBuffer(audioBuffer)

If I convert the audio to stereo, everything works.

andlin
  • 3,534
  • 3
  • 25
  • 43

0 Answers0