3
votes

I need to have have audio (a lecture etc.) recording on iPhone and directly playing back through the headphones.

I have code that works - most of the time!

  1. I set up my AVAudioSession

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];

  2. I set up my player and recorder, both pointing to the same URL.

    audioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&error];

    //set up audio playing audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:&error];

  3. I prepare to play and record

    [audioRecorder prepareToRecord]; [audioPlayer prepareToPlay];

Everything proceeds well for a while. Then suddenly, the player stops, and its current time goes to zero.

It doesn't look like its getting dealloc'ed, since I can proceed to play the recorded sound just fine from the start position. The stopping occurs seemingly randomly, at different times each time.

Anyone have any suggestions as to what the problem is or how to debug?

Thanks in advance!

1
This seems like a race condition. If the recorder doesn't insert data fast enough then the player will reach the end and stop. Have a look at this question: stackoverflow.com/questions/7184341/…borrrden

1 Answers

2
votes

To summarize the following ramble: in my experience, the AVAudioPlayer will only play for as long long as the file had data, when it was initialized.

I'm struggling with the same thing; I wonder if you ever found a good solution. I'm working on a similar project (I want to be able to record, and playback with a small delay, while recording).

I start by creating an AVAudioRecorder, which works fine. Then I start up an AVAudioPlayer with initWithContentsOfURL, pointing to the same file.

What I have found is that if there were, say, 3 seconds of sound (via the .duration property) in that file when the player starts, it will stop after 3 seconds, even if the AVAudioRecorder has continued after that.

I've attempted to work around this by creating a second player once the first nears the end of the initial duration of the recording, but this results in a small dropout of audio that I can seem to rid myself of.

If only we could tell AVAudioPlayer to keep reading the file!