这篇博客将简单介绍如何使用系统的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
- (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]);
}
好了,简单的录音与播放就实现啦,有不清楚的请留言哦