3

I'm writing an iOS application in Swift which is recording user's voice and than can play it back with some voice effects, but the problem is that the playback is very silent when using built-in iPhone microphone. With headphones there is no problem.

Recording code:

let recordingName = "my_audio.m4a"
let pathArray = [dirPath, recordingName]
let filePath = NSURL.fileURLWithPathComponents(pathArray)
print(filePath)

let recordSettings: [String: AnyObject] = [
    AVFormatIDKey: Int(kAudioFormatAppleLossless),
    AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
    AVEncoderBitRateKey : 320000,
    AVNumberOfChannelsKey: 2,
    AVSampleRateKey : 44100.0
]

let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord)
try! audioRecorder = AVAudioRecorder(URL: filePath!, settings: recordSettings)

audioRecorder.meteringEnabled = true
audioRecorder.updateMeters()
audioRecorder.delegate = self
audioRecorder.prepareToRecord()
audioRecorder.record()

Playback code:

playerNode.stop()
playerNode.volume = 1.0
audioEngine.stop()
audioEngine.reset()

audioEngine.attachNode(playerNode)
audioEngine.attachNode(audioUnitTime)
audioEngine.connect(playerNode, to: audioUnitTime, format: receivedAudio.processingFormat)
audioEngine.connect(audioUnitTime, to: audioEngine.outputNode, format: receivedAudio.processingFormat)

playerNode.scheduleFile(receivedAudio, atTime: nil, completionHandler: nil)
try! audioEngine.start()
playerNode.play()

The only trace of solution for me is that the original apple voice recording app does the same but only when the upper right corner speaker icon is disabled. Though I wasn't able to find out what that speaker icon does.

Floern
  • 33,559
  • 24
  • 104
  • 119
Ernest Zamelczyk
  • 2,562
  • 2
  • 18
  • 32

1 Answers1

7

Alright I found it finally. The problem was with the AVAudioSession:

let session = AVAudioSession.sharedInstance()
try! session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions:AVAudioSessionCategoryOptions.DefaultToSpeaker)
Ernest Zamelczyk
  • 2,562
  • 2
  • 18
  • 32
  • I am trying the sample. If I started to recognise my speech via microphone, then I tried to get iPhone's voice of that recognised text. It is working. But, voice is too low. Can u guide me on this? – McDonal_11 Jul 28 '17 at 10:34
  • https://stackoverflow.com/questions/45371931/swift-iphones-volume-is-low-when-trying-to-change-speech-to-iphones-voice-in My question.... – McDonal_11 Jul 28 '17 at 11:11