@julop, @nevos, @TatianaMrl: are you really starting recording in the background? Do you have any specific background modes enabled that you can share or are you not using AudioQueueStart?
Here is some of my code and we still get return status AVAudioSessionErrorCodeCannotStartRecording is we start recording in background.
We are starting recording using a Bluetooth 4.0 accessory and I am cursious if this could be the problem for us.
We have done some battery measurements to keep recording enabled at all times and just drop the data until we need to process it. This has a great impact on battery life. On our particular test devices it had this effect:
Apple iPhone 6S Plus. Battery life went from 62h to 41h which is a decrease of 34% (https://www.dropbox.com/s/uyy3rwzzlzzf478/I3%20-%20Apple%20iPhone%206S%20Plus%20%28Apple%20iPhone8%2C2%29%20iOS%2012.4.1.jpg?dl=0)
Apple iPhone 7. Battery life went from 28h to 14h which is a decrease of 50% (https://www.dropbox.com/s/wt9wwmaezru6mtj/I5%20-%20Apple%20iPhone%207%20%28Apple%20iPhone9%2C3%29%20iOS%2013.1.jpg?dl=0)
Apple iPhone 6S. Battery life went from 33h to 27h which is a decrease of 18% (https://www.dropbox.com/s/vuaqgthvnsfh4tf/I6%20-%20Apple%20iPhone%206S%20%28Apple%20iPhone8%2C1%29%20iOS%2013.1.jpg?dl=0)
Here is the method we use to start the recording
- (void)startRecording {
aqData.mDataFormat.mFormatID = kAudioFormatMPEG4AAC;
aqData.mDataFormat.mSampleRate = 22050.0;
aqData.mDataFormat.mChannelsPerFrame = 1;
aqData.mDataFormat.mBitsPerChannel = 0;
aqData.mDataFormat.mBytesPerPacket = 0;
aqData.mDataFormat.mBytesPerFrame = 0;
aqData.mDataFormat.mFramesPerPacket = 1024;
aqData.mDataFormat.mFormatFlags = kMPEG4Object_AAC_Main;
AudioFileTypeID fileType = kAudioFileAAC_ADTSType;
aqData.bufferByteSize = 16384;
UInt32 defaultToSpeaker = TRUE;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof(defaultToSpeaker), &defaultToSpeaker);
OSStatus status = AudioQueueNewInput(&aqData.mDataFormat, HandleInputBuffer, &aqData, NULL, kCFRunLoopCommonModes, 0, &aqData.mQueue);
UInt32 dataFormatSize = sizeof (aqData.mDataFormat);
status = AudioQueueGetProperty(aqData.mQueue, kAudioQueueProperty_StreamDescription, &aqData.mDataFormat, &dataFormatSize);
status = AudioFileInitializeWithCallbacks(&aqData, nil, BufferFilled, nil, nil, fileType, &aqData.mDataFormat, 0, &aqData.mAudioFile);
for (int i = 0; i < kNumberBuffers; ++i) {
status = AudioQueueAllocateBuffer (aqData.mQueue, aqData.bufferByteSize, &aqData.mBuffers[i]);
status = AudioQueueEnqueueBuffer (aqData.mQueue, aqData.mBuffers[i], 0, NULL);
}
aqData.mCurrentPacket = 0;
aqData.mIsRunning = true;
status = AudioQueueStart(aqData.mQueue, NULL);
}