如何在iphone中录制语音和播放

时间:2012-04-17 11:08:18

标签: iphone

我在项目中实现了录音功能,但我无法控制停止和丢弃按钮。在第二次单击丢弃按钮后无法录制语音。 点击放弃后,音频文件也在播放,无法再次点击开始按钮。

请帮助解决这个问题

这是源代码

.h file

@interface VoiceInput : UIViewController
                                 <AVAudioRecorderDelegate>
{
//Audio record

  float remainingDelayTime;
  float remainingRecordTime;
  UILabel *delayLabel;

  UIProgressView *progressView;
  AVAudioRecorder *recorder;
  NSTimer *delayTimer;
  NSTimer *recordTimer;
  BOOL toggle;
  NSURL *recordedTmpFile;
  NSError *error;
}
@property (nonatomic, retain) AVAudioRecorder *recorder;
@property (nonatomic, retain) NSTimer *delayTimer;
@property (nonatomic, retain) NSTimer *recordTimer;
@end

.m file

@implementation VoiceInput
@synthesize progressView;
@synthesize recorder;
@synthesize delayTimer;
@synthesize recordTimer;

- (void)viewDidLoad
{
    toggle = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    [audioSession setActive:YES error:&error];
}

-(void)startPushed
{
   if (toggle)
    {
        remainingDelayTime = 4.0;
        delayTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                      target:self
                                                    selector:@selector(delayTimerFired:)
                                                    userInfo:nil
                                                     repeats:YES];
        toggle = NO;
        NSMutableDictionary *rs = [[NSMutableDictionary alloc] init];
        [rs setValue:[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];
        [rs setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
        [rs setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
        recordedTmpFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%.0f.%@", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @"caf"]]];
        NSLog(@"USING FILE CALLED: %@", recordedTmpFile);

        recorder = [[AVAudioRecorder alloc] initWithURL:recordedTmpFile settings:rs error:&error];
        [recorder setDelegate:self];
        [recorder prepareToRecord];
        [recorder record];

    }
    else
    {
        toggle = YES;
        NSLog(@"Using File Called: %@", recordedTmpFile);
        [recorder stop];
    }


  self.discardButton.enabled = NO;
  self.startButton.enabled = NO;
  self.stopButton.enabled = YES;

}

-(void)stopPushed
{
if([self.recorder isRecording])
  {
    [self.recorder stop];

    if(remainingRecordTime >= 1.0)
    {
      [self.recordTimer invalidate];
    }
}
self.delayLabel.textColor = [UIColor darkGrayColor];
 self.delayLabel.text = [[NSString alloc] initWithFormat:@"Record in ..."];

  self.discardButton.enabled = YES;
  self.playbackButton.enabled = YES;
  self.startButton.enabled = NO;
  self.stopButton.enabled = NO;

}

-(void)playbackPushed
{ 
  AVAudioPlayer *avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:recordedTmpFile    error:&error];
    [avPlayer prepareToPlay];
    [avPlayer play];

  self.discardButton.enabled = YES;
  self.playbackButton.enabled = YES;
  self.returnButton.enabled = YES;
  self.startButton.enabled = YES;
  self.stopButton.enabled = YES;

}

-(void)discardPushed
{
  [self.recorder deleteRecording];
  self.progressView.progress = 0;
  self.delayLabel.textColor = [UIColor darkGrayColor];
  self.delayLabel.text = @"Record in ...";

  self.discardButton.enabled = NO;
  self.playbackButton.enabled = NO;
  self.startButton.enabled = YES;
  self.stopButton.enabled = YES;

}

-(void)delayTimerFired:(NSTimer *)theDelayTimer
{
  self.progressView.progress = 0;
  remainingDelayTime -= 1.0;
  NSLog(@"fired %f", remainingDelayTime);
  self.delayLabel.textColor = [UIColor blackColor];
  self.delayLabel.text = [[NSString alloc] initWithFormat:@"Record in %2.0f",
                            remainingDelayTime];

  if(remainingDelayTime <= 0.0)
  {
    [self.delayTimer invalidate];
    self.delayLabel.text = [[NSString alloc] initWithFormat:@"Recording"];

    [self.recorder recordForDuration:TIME];
    remainingRecordTime = TIME;
    recordTimer = [NSTimer scheduledTimerWithTimeInterval:TIME_DECREMENT
                                             target:self
                                           selector:@selector(recordTimerFired:)
                                           userInfo:nil
                                            repeats:YES];
  }

}

-(void)recordTimerFired:(NSTimer *)theRecordTimer
{
  remainingRecordTime -= TIME_DECREMENT;
  NSLog(@"fired %f", remainingRecordTime);
  self.progressView.progress = (TIME - remainingRecordTime)/TIME;

  if(remainingRecordTime <= 0.0)
  {
    [self.recordTimer invalidate];
  }

}

提前致谢

1 个答案:

答案 0 :(得分:2)

看看这个。你可以通过这个开始录音: -

- (void) startRecording
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
    [audioSession setMode:AVAudioSessionModeVoiceChat error:&err];

    if(err)
    {
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }

    [audioSession setActive:YES error:&err];
    err = nil;

    if(err)
    {
        NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        return;
    }

    recordSetting = [[NSMutableDictionary alloc] init];

    // We can use kAudioFormatAppleIMA4 (4:1 compression) or kAudioFormatLinearPCM for nocompression
    [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatAppleIMA4] forKey:AVFormatIDKey];

    // We can use 44100, 32000, 24000, 16000 or 12000 depending on sound quality
    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];

    // We can use 2(if using additional h/w) or 1 (iPhone only has one microphone)
    [recordSetting setValue:[NSNumber numberWithInt: 1] forKey:AVNumberOfChannelsKey];

    [recordSetting setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey];
    [recordSetting setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    [recordSetting setObject:[NSNumber numberWithInt: AVAudioQualityMax] forKey: AVEncoderAudioQualityKey];  

    NSString *str;
    str = [NSString stringWithFormat:@"%@/MySound.caf",DOCUMENTS_FOLDER];


    NSLog(@"recorderFilePath: %@",str);

    NSURL *url = [NSURL fileURLWithPath:str];

    err = nil;
    recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
    if(!recorder)
    {
        NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: [err localizedDescription]
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];

        return;
    }

    //prepare to record
    [recorder setDelegate:self];
    [recorder prepareToRecord];
    recorder.meteringEnabled = YES;

    BOOL audioHWAvailable = audioSession.inputIsAvailable;
    if (! audioHWAvailable) {
        UIAlertView *cantRecordAlert =
        [[UIAlertView alloc] initWithTitle: @"Warning"
                                   message: @"Audio input hardware not available"
                                  delegate: nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [cantRecordAlert show];

        return;
    }

    // start recording
    [recorder recordForDuration:(NSTimeInterval) 20];
    }

这将开始录音。之后你可以停止录音: -

- (void) stopRecording
{
[recorder stop];
}

现在您可以通过以下方式播放录音: -

- (void)playRecordingSound
{
if(!recorderFilePath)
    recorderFilePath = [NSString stringWithFormat:@"%@/MySound.caf", DOCUMENTS_FOLDER] ;
    if(soundID)
{
    AudioServicesDisposeSystemSoundID(soundID);
}

//Get a URL for the sound file
NSURL *filePath = [NSURL fileURLWithPath:recorderFilePath isDirectory:NO];

//Use audio sevices to create the sound
AudioServicesCreateSystemSoundID((__bridge CFURLRef)filePath, &soundID);

//Use audio services to play the sound
AudioServicesPlaySystemSound(soundID);

}

希望它有所帮助谢谢:)