IOS 音频录制与播放简单演示

这篇博客将简单介绍如何使用系统的API实现录音与播放功能,全部代码都会贴上。

1、创建工程,添加依赖包



2、在Main.storyboard 里面添加三个按钮,并连线ViewController 



3、 添加代理,并创建播放器,录音器实例对象

@interface ViewController ()<AVAudioPlayerDelegate,AVAudioRecorderDelegate>
@property(strong,nonatomic)AVAudioPlayer *audioPlayer;
@property(nonatomic,strong)AVAudioRecorder *recorder;
//保存录音时生成的resourceId
@property(nonatomic,strong)NSString *resourceId;
@end


4、实现方法

- (void)viewDidLoad {
    [super viewDidLoad];
    [_stopBtn setEnabled:NO];
    [_playBtn setEnabled:NO];
    // Do any additional setup after loading the view, typically from a nib.
}

录音、播放控制方法实现:

#pragma mark IBAction Function
- (IBAction)recordBegin:(id)sender {
    if(self.recorder.isRecording){
        NSLog(@"isRecording now!");
        return;
    }
    [self beginRecord];
}

- (IBAction)recordStop:(id)sender {
    [self.recorder stop];
    self.recorder = nil;
    NSLog(@"stop record !");
}

- (IBAction)playMusic:(id)sender {
    NSString *filePath = [self pathWithResource:_resourceId];
    if(filePath){
        
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        [audioSession setActive:YES error:nil];
        NSURL *audioURL = [NSURL fileURLWithPath:filePath];
        NSError *error ;
        self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error];
        if(error){
            NSLog(@"audioPlayer init error:%@",[error localizedDescription]);
        }
        [self.audioPlayer setDelegate:self];
        [self.audioPlayer setVolume:1];
        [self.audioPlayer prepareToPlay];
        [self.audioPlayer play];
    }
}

#pragma mark UserDefine Function

-(void)beginRecord{
     NSLog(@"start record !");
    [_startBtn setEnabled:NO];
    [_stopBtn setEnabled:YES];
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                              [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                              nil];
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    _resourceId = [[NSUUID UUID] UUIDString];
    NSString *filePath = [self pathWithResource:_resourceId];
    NSURL *fileUrl=[NSURL fileURLWithPath:filePath];
    NSError *error;
    self.recorder=[[AVAudioRecorder alloc]initWithURL:fileUrl settings:settings error:&error];
    [self.recorder prepareToRecord];
    [self.recorder record];
    self.recorder.delegate = self;
}

-(NSString *)pathWithResource:(NSString*)resourceId{
    NSString *docPath = [self getdocumentsFolder];
    NSString *dirPath = [docPath stringByAppendingPathComponent:@"Resource"];
    NSString *filePath = [dirPath stringByAppendingPathComponent:resourceId];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = false;
    BOOL isDirExist = [fileManager fileExistsAtPath:dirPath isDirectory:&isDir];
    if(!isDirExist){
        NSLog(@"Resource 文件夹不存在,需要创建文件夹!");
      isDirExist = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if(isDirExist){
      //  NSLog(@"文件夹之前就存在或者文件夹这次创建成功都会返回文件全路径!");
        return filePath;
    }
    return nil;
}

- (NSString *) getdocumentsFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}


录音播放的代理方法实现:

#pragma mark AVAudioRecorderDelegate

-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    [[AVAudioSession sharedInstance] setActive:NO error:nil];
    NSLog(@"audioRecorderDidFinishRecording success record");
    [_startBtn setEnabled:YES];
    [_playBtn setEnabled:YES];
    [_stopBtn setEnabled:NO];
}

-(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error{
     NSLog(@"audioRecorderEncodeErrorDidOccur :%@",[error localizedDescription]);
    [_startBtn setEnabled:YES];
    [_playBtn setEnabled:NO];
    [_stopBtn setEnabled:NO];
}

#pragma mark AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    NSLog(@"audioPlayerDidFinishPlaying success playing");
    [[AVAudioSession sharedInstance] setActive:NO error:nil];
    self.audioPlayer = nil;
    [_startBtn setEnabled:YES];
    [_playBtn setEnabled:YES];
    [_stopBtn setEnabled:NO];
    
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    NSLog(@"audioPlayerDecodeErrorDidOccur :%@",[error localizedDescription]);
    
}


好了,简单的录音与播放就实现啦,有不清楚的请留言哦





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值