开发者

Setting a time limit when recording an audio clip?

I looked for search terms along the lines of the post title, but alas..

I am building an iPhone app using AVFoundation.

开发者_StackOverflow

Is there a correct procedure to limit the amount of audio that will be recorded? I would like a maximum of 10 seconds.

Thanks for any help/advice/tips/pointers..


AVAudioRecorder has the following method:

- (BOOL)recordForDuration:(NSTimeInterval)duration

I think that will do the trick!

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html#//apple_ref/doc/uid/TP40008238


I don't normally work with AVFoundation so I don't know the exact method/class names (I filled in my own), but a workaround to this would be having a recurring NSTimer beginning when the recording originally starts. Something like this:

@interface blahblah
...
int rec_time;
NSTimer *timer;
Recorder *recorder;
...
@end

@implementation blahblah
...
-(void)beginRecording {
    [recorder startRecording];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0
    target:self
    selector:@selector(recordingTime)
    userInfo:nil
    repeats:YES];
}

-(int)recordingTime {
    if (rec_time >= 10) {
        [recorder endRecording];
        [timer invalidate];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You recorded for too long!"...;
        return;
    }

    rec_time = rec_time + 1;

}
...
@end


This is an example from the iOS Programming Cookbook, i found it very useful and straigtforward. After starting to record, you call the stop function with delay of 10 seconds, when it stops recording it will automatically call the delegate method audioRecorderDidFinishRecording:successfully.

@implementation ViewController{

   AVAudioRecorder *recorder;
   AVAudioPlayer *player;
}   

- (IBAction)recordPauseTapped:(id)sender {
// Stop the audio player before recording
   if (player.playing) {
     [player stop];
   }

   if (!recorder.recording) {
      AVAudioSession *session = [AVAudioSession sharedInstance];
      [session setActive:YES error:nil];

      // Start recording
      [recorder record];

     [recordPauseButton setBackgroundImage:recordingImage forState:UIControlStateNormal];
     [self performSelector:@selector(stopRecording)
               withObject:self afterDelay:10.0f];

     } else {
       [recorder stop];

       AVAudioSession *audioSession = [AVAudioSession sharedInstance];
       [audioSession setActive:NO error:nil];
     }
} 

- (void)stopRecording {
  [recorder stop];

  AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  [audioSession setActive:NO error:nil];
}

 - (void) audioRecorderDidFinishRecording:(AVAudioRecorder *)avrecorder    successfully:(BOOL)flag{
    NSLog(@"after 10 sec");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜