ios录音、音频播放功能

时间:2023-03-08 18:28:42
ios录音、音频播放功能

#import <AVFoundation/AVFoundation.h>

{

NSInteger   _timeCount;
    NSTimer     *_timer;

}

@property(nonatomic,retain)AVAudioPlayer  *audioPlayer;
@property(nonatomic,retain)AVAudioRecorder *recorder;
@property(nonatomic,assign)NSInteger      playTag;

/**
 *  创建录音机
 */
-(AVAudioRecorder *)recorder{
    if (!_recorder) {
        NSURL *url = [self filePath];
        NSDictionary *setting = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:AVAudioQualityMin],AVEncoderAudioQualityKey,[NSNumber numberWithInt:16],AVEncoderBitRateKey,[NSNumber numberWithInt:2],AVNumberOfChannelsKey,[NSNumber numberWithFloat:44100.0],AVSampleRateKey,nil];
        NSError *error=nil;
        _recorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _recorder.delegate=self;
        _recorder.meteringEnabled=YES;
        if (error) {
            NSLog(@"录音错误:%@",error.localizedDescription);
        }
        [_recorder prepareToRecord];
    }
    return _recorder;
}

//返回文件的路径
-(NSURL *)filePath
{
    NSString *strPath=[NSTemporaryDirectory() stringByAppendingPathComponent:@"aaa.caf"];
     NSLog(@"%@-----------",strPath);
    NSURL *url=[NSURL fileURLWithPath:strPath];
    return url;
}

//弹出录音页面

-(void)addAudioView{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    _backView = [[ UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    _backView.alpha = 0.5;
    _backView.backgroundColor = [ UIColor blackColor];
    [self.view addSubview:_backView];
    
    _audioView  = (AudioRecorderAlterView *)[[[NSBundle mainBundle]loadNibNamed:@"AudioRecorderAlterView" owner:nil options:nil]lastObject];
    _audioView.frame = CGRectMake(0, 64, 200, 200);
    _audioView.center = CGPointMake(self.view.center.x, 200);
    [_audioView.EndBtn addTarget:self action:@selector(pulishVedio) forControlEvents:UIControlEventTouchUpInside];
    [_audioView.CannelBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_audioView];
}

//点击录音按钮

- (IBAction)vedioBtnClick:(id)sender {
    if ([_audioPlayer isPlaying]) {
        [_audioPlayer stop];
        UIImageView *animationImageView_last = (UIImageView  *)[self.view viewWithTag:_playTag  + 10000];
        [animationImageView_last stopAnimating];
    }

if ([self canRecord]) {
        [self addAudioView];
        if (![self.recorder isRecording]) {
            [self.recorder record];
        }
        [self addTimer];
    }
}