Search code examples
iosavaudioplayeravaudiorecorderaac

Record & play audio in AAC format iOS 5 +


I want to record the voice in iOS & play it. Also I want to send recorded file to server. I have one twist that recorded file MUST play on ANDROID devices also. So I tried using MP3 . But AVAudioRecorder doesn't allow MP3 folrmat for recording. So I have used AAC. But its not working. Here is my code

    -(void)initializeAudioRecorder {

    self.btnPlayRecording.enabled = NO;
    self.btnStopRecording.enabled = NO;

    // Get sound file URL in which recording is saved
    NSURL *soundFileURL = [NSURL fileURLWithPath:[self soundFilePath]];

    // Set settings for audio recording
    NSDictionary *audioRecordSettings = [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:AVAudioQualityMin],AVEncoderAudioQualityKey,
        [NSNumber numberWithInt:16],AVEncoderBitRateKey,
        [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
        [NSNumber numberWithFloat:44100.0],AVSampleRateKey,
        [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey, nil];

    NSError *error = nil;
    self.audioRecorder = [[AVAudioRecorder alloc]
                     initWithURL:soundFileURL
                     settings:audioRecordSettings
                     error:&error];

    if (error)
    {
        NSLog(@"error: %@", [error localizedDescription]);
    } 
    else {
        if (![self.audioRecorder prepareToRecord]) {
            NSLog(@"Failed to prepare recording");
        }
    }
}

    #pragma mark - Get Sound File Path

-(NSString*)soundFilePath {

    NSArray *dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docsDirPath = [dirPaths objectAtIndex:0];
    NSString *soundFilePath = [docsDirPath stringByAppendingPathComponent:@"testSound.aac"];
    return soundFilePath;
}


#pragma mark - IBAction Methods

- (IBAction)btnStartRecordingTapped:(id)sender {

    if (!self.audioRecorder.recording) {
        self.btnPlayRecording.enabled = NO;
        self.btnStopRecording.enabled = YES;
        [self.audioRecorder record];
    }
}

- (IBAction)btnStopRecordingTapped:(id)sender {

    self.btnStopRecording.enabled = NO;
    self.btnPlayRecording.enabled = YES;
    self.btnStartRecording.enabled = YES;
}

- (IBAction)btnPlayRecordingTapped:(id)sender {

    if (!audioRecorder.recording) {
        self.btnStopRecording.enabled = YES;
        self.btnStartRecording.enabled = NO;
        NSError *error = nil;

        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:self.audioRecorder.url error:&error];
        self.audioPlayer.delegate = self;

        if (error) {
            NSLog(@"Error occured while playing recorded audio.\nError:- %@",[error localizedDescription]);
        }
        else {
            [self.audioPlayer play];
        }

    }
}

#pragma mark - AVAudioPlayer Delegate MEthods

/* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
    self.btnStartRecording.enabled = YES;
    self.btnStopRecording.enabled = NO;
}

/* if an error occurs while decoding it will be reported to the delegate. */
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
    NSLog(@"audioPlayerDecodeError:- %@",[error localizedDescription]);
}

#pragma mark - AVAudioRecorder Delegate MEthods

/* audioRecorderDidFinishRecording:successfully: is called when a recording has been finished or stopped. This method is NOT called if the recorder is stopped due to an interruption. */
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
}

/* if an error occurs while encoding it will be reported to the delegate. */
- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    NSLog(@"In %s",__PRETTY_FUNCTION__);
    NSLog(@"audioRecorderEncodeError:- %@",[error localizedDescription]);
}

But above code is not recording audio. File gets created at DOCS dir. But when I tried to play it, its not working. I can't hear anything.

Whats wrong in my code ? Also is there any library for recording & playing audio in format which will play on iOS + Android ? Thanks


Solution

  • This worked for me:

    1. Ensure that the device volume is high enough:

      MPMusicPlayerController * musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
      if (musicPlayer.volume < 1.0) {
            musicPlayer.volume = 1; // device volume will be changed to maximum value
      }
      musicPlayer = nil;
      
    2. Using AVAudioSession:

      AVAudioPlayer * meinPlayer = [[AVAudioPlayer alloc]
                        initWithContentsOfURL:soundFileURL
                        error:&error];
      meinPlayer.delegate = self;
      
      [meinPlayer prepareToPlay]
      AVAudioSession *session = [AVAudioSession sharedInstance];
      [session setCategory:AVAudioSessionCategoryPlayback error:nil];
      [session setActive:YES error:nil];
      [meinPlayer play];