3

I'm using AVAudioEngine to capture users' voice and apply some effects to it.When recording with headphone's mic , everything goes well. But when it comes to recording with phone's built-in mic , and playback the sound through headphone , only the left-side earbud has the sound, it seems the built-in mic only have single channel input. So how can I fix this issue? Here's some of my code:

func connectNode(){
  engine.connect(engine.inputNode!, to: reverbNode, format:reverbNode.outputFormatForBus(0))
  engine.connect(reverbNode, to: delayNode, format: delayNode.outputFormatForBus(0))
  engine.connect(delayNode, to: distortion, format: distortion.outputFormatForBus(0))
  engine.connect(distortion, to: engine.mainMixerNode, format: engine.mainMixerNode.outputFormatForBus(0))
  engine.connect(player, to: engine.mainMixerNode, format: engine.mainMixerNode.outputFormatForBus(0))
}

func recordToFile(){
  setSessionRecord()
  recordSetting[AVFormatIDKey] = NSNumber(unsignedInt: UInt32(kAudioFormatMPEG4AAC))
  recordSetting[AVNumberOfChannelsKey] = NSNumber(int: 2)
  var file: AVAudioFile!
  do{
    try file = AVAudioFile(forWriting: URLFor(fileName)!, settings: recordSetting)
  }catch let error as NSError{
  print("error:\(error)")
  }
  engine.mainMixerNode.installTapOnBus(0, bufferSize: 1024, format: file.processingFormat) { (buffer, time) -> Void in
  try! file.writeFromBuffer(buffer)
  }
}

func playbackRecord(){
  setSessionPlayback()
  var file:AVAudioFile!
  file = try! AVAudioFile(forReading:URLFor(fileName)!)
  let audioFormat = file.processingFormat
  let audioFrameCount = UInt32(file.length)
  let audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount)
  try! file.readIntoBuffer(audioFileBuffer, frameCount: audioFrameCount)
  player.scheduleBuffer(audioFileBuffer, atTime: nil, options: .Interrupts, completionHandler: {print(self.player.stop())})
  if(!player.playing){
    player.play()
  }else{
    print("stop")
    player.stop()
  } 
}
Keater
  • 123
  • 2
  • 9

1 Answers1

2

I found a way to fix this issue.Just modify this method to give the engine a single channel format and then everything will be fine.

func connectNode(){
  let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatFloat32, sampleRate: 44100.0, channels:AVAudioChannelCount(1), interleaved: false)
  engine.connect(engine.inputNode!, to: reverbNode, format:format)
  engine.connect(reverbNode, to: delayNode, format: format)
  engine.connect(delayNode, to: distortion, format: format)
  engine.connect(distortion, to: engine.mainMixerNode, format: format)
  engine.connect(player, to: engine.mainMixerNode, format: engine.mainMixerNode.outputFormatForBus(0))
}
Keater
  • 123
  • 2
  • 9