background audio recording in iOS

2019-02-20 17:17发布

问题:

I have searched far and wide for documentation on how to record audio in the background and have come to the conclusion that specifying 'audio' in the plist file might work. But, because iOS 4 will terminate background apps when it runs low on memory, we must also take some steps to reduce our memory usage when we transition to the background. How do we reduce our memory usage?

Also, does anybody know a sure shot way of recording audio in the background on iOS??

I unchecked the box in the Info.plist file that says "Application does not run in background" and also added the

<key> UIBackgroundModes </ key> < array> < string> audio</ string></ array>

in Info.plist. But, the recording stops as soon as I press the "HOME" button.

What callbacks do we implement to know that application has gone to background? Please advise.

回答1:

Just in case anyone else is looking for an answer here, I got mine working by adding the UIBackgroundModes array to the plist, adding 'audio' as Item 0.

I free up all memory/controllers on exit as you would by quitting the app anyhow so all that is left are the buffers the app uses (I've allocated around 1Mb though which makes me a little nervous however it seems to have worked!) I guess reducing the fidelity would help too but it seems to work as is.

In my core Audio setup I had to either change the buffer size from 1024 to 4096 or explicitly set the buffer size... I opted for the latter as latency was an issue.

NSTimeInterval iobuffersize = (float)1024.0f/SAMPLE_RATE);
sizeofdata = sizeof(iobuffersize);
AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, &sizeofdata, &iobuffersize);

I also had to make sure that it didn't kill the app on exit via not enabling the 'Does not run in background' option however this should be off by default anyhow.

So guess I'm answering this for peace of mind for anyone else that it does work with not much setup after all.

I am however experiencing problems with Bluetooth setup, I guess that's because the buffer sizes change again but can't figure this one out... just get -50 = invalid property warning when rendering the data via the recordingCallback. I'm guessing it's the freq/sample size but who knows... will look later but seems like background now works.



回答2:

Apart from specifying background recording in the plist file, we can implement applicationDidEnterBackground wihch will tell us when the application enters background. Here, we should stop any updates to the UI because that consumes memory for eg, updating a timer and an equalizer.

The call applicationWillEnterForeground will be called just before the app returns to foreground so we can resume whatever we stopped.

The recording then takes place in the background. It would also help to implement an interruption listener(this would work in the backgroud as well) so that you don't lose your recordings.