录音

录音

1.#import "ViewController.h"
2.#import "CDMyUtil.h"
3.#import <AVFoundation/AVFoundation.h>
4.
5.@interface ViewController () {
6. AVAudioRecorder *myRecorder;
7.
8. NSDictionary *dict;
9.}
10.
11.@end
12.
13.@implementation ViewController
14.
15.- (void)viewDidLoad {
16. [super viewDidLoad];
17.
18. // 对AVAudioRecorder对象的设置
19. dict = @{
20. AVEncoderAudioQualityKey:[NSNumber numberWithInt:AVAudioQualityLow],
21. AVEncoderBitRateKey:[NSNumber numberWithInt:16],
22. AVNumberOfChannelsKey:[NSNumber numberWithInt:2],
23. AVSampleRateKey:[NSNumber numberWithInt:44100]
24. };
25.
26. NSLog(@"%@", NSHomeDirectory());
27.}
28.
29.- (IBAction)recordButtonClicked:(UIButton *)sender {
30. if (!myRecorder) {
31. // 指定一个文件路径
32. NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.caf", [CDMyUtil timeStringWithFormat:@"yyyyMMddHHmmssSSS"]]];
33. // 通过文件路径获得文件的URL
34. NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
35. // 创建AVAudioRecorder对象
36. myRecorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:dict error:nil];
37. }
38.
39.
40. if (myRecorder.isRecording) {
41. [myRecorder stop]; // 结束录制
42. [sender setTitle:@"录音" forState:UIControlStateNormal];
43. myRecorder = nil;
44. }
45. else {
46. [myRecorder prepareToRecord];
47. [myRecorder record]; // 开始录制
48. [sender setTitle:@"结束" forState:UIControlStateNormal];
49. }
50.}
51.
52.@end
53.
 
原文地址:https://www.cnblogs.com/buakaw/p/5211340.html