代碼:
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()
/** 錄音對象 */
@property (nonatomic, strong) AVAudioRecorder *recorder;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)startBtn {
// 6.開始錄音
[self.recorder record];
}
- (IBAction)stopBtn {
// 結(jié)束錄音
[self.recorder stop];
}
#pragma mark - 懶加載代碼
- (AVAudioRecorder *)recorder{
if (_recorder == nil) {
// 1.創(chuàng)建沙盒路徑
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",path);
// 2.拼接音頻文件
NSString *filePath = [path stringByAppendingPathComponent:@"123.caf"];
// 3.轉(zhuǎn)化成URL
NSURL *url = [NSURL fileURLWithPath:filePath];
// 4.設(shè)置錄音的參數(shù)
NSDictionary *settingRecorder = @{
AVEncoderAudioQualityKey : [NSNumber numberWithInteger:AVAudioQualityLow],
AVEncoderBitRateKey : [NSNumber numberWithInteger:16],
AVSampleRateKey : [NSNumber numberWithFloat:8000],
AVNumberOfChannelsKey : [NSNumber numberWithInteger:2]
};
// 5.創(chuàng)建錄音對象
self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:settingRecorder error:nil];
}
return _recorder;
}