Search code examples
iphoneiosxcodeformatavaudiorecorder

I want iLBC format, but can only seem to record audio in IMA4 format


How do I record audio in iLBC format? I got some help from Question #1010343, and implemented this code:

NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] initWithCapacity:10];        
[recordSetting setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
//  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];  //  doesn't work:  no error, but no sound
//  [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatiLBC] forKey:AVFormatIDKey];  //  doesn't work:  no error, but not sound
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
[recordSetting setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
[recordSetting setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey];
recorder = [[AVAudioRecorder alloc] initWithURL:audioFile settings:recordSetting error: &avError ];
[recorder setDelegate:self];
[recorder recordForDuration:(NSTimeInterval) secLeft];
[recorder record];

Like above, it works fine. Good recording. Easy playback. You notice the other formats commented out. If I try either of them, I get nothing. I want smaller files, and according to Question #7279643, which gives this valuable info:

Here are the results for few encoding supported by iPhone:
Size of audio file of duration 10 sec.
   kAudioFormatMPEG4AAC :      164 kB
   kAudioFormatAppleLossless : 430 kB
   kAudioFormatAppleIMA4 :     475 kB
   kAudioFormatULaw :          889 kB
   kAudioFormatALaw :          889 KB

I should be able to record in iLBC. But if I try, I get nothing. Is there something else that I need to change either in recording or playback when I use a format other than IMA4 format?

Here's my playback code:

NSError     *avError;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&avError];
[audioSession setActive:YES error:&avError];
if( !avError ) {
    if( [audioPlayer isPlaying] ) {
        [audioPlayer stop ];
    }
    while( ![audioPlayer isPlaying] ) {
        AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:audioFile  error:nil];
        self.audioPlayer = player;
        self.audioPlayer.numberOfLoops = 0;
        [audioPlayer prepareToPlay];
        [audioPlayer play];
    }
} else {
    NSLog(@"Playback Error: %@", avError );
}

Solution

  • Fixed it by removing:

    [recordSetting setValue:[NSNumber numberWithFloat:44100.0]forKey:AVSampleRateKey]; 
    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey]
    

    I guess they conflict with the iLBC defaults.