IOS 音訊錄製與播放簡單演示

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]);
}

好了,簡單的錄音與播放就實現啦,有不清楚的請留言哦