码迷,mamicode.com
首页 > 移动开发 > 详细

IOS-录音

时间:2016-03-22 19:20:13      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

 

 1 //
 2 //  ViewController.m
 3 //  IOS_0322_录音
 4 //
 5 //  Created by ma c on 16/3/22.
 6 //  Copyright © 2016年 博文科技. All rights reserved.
 7 //
 8 
 9 #import "ViewController.h"
10 #import <AVFoundation/AVFoundation.h>
11 
12 @interface ViewController ()
13 
14 @property (nonatomic, strong) AVAudioRecorder *recorder;
15 @property (nonatomic, strong) CADisplayLink *timer;
16 @property (nonatomic, assign) CGFloat silentDuration;
17 
18 
19 - (IBAction)startRecord;
20 - (IBAction)stopRecord;
21 
22 @end
23 
24 @implementation ViewController
25 
26 - (void)viewDidLoad {
27     [super viewDidLoad];
28     // Do any additional setup after loading the view, typically from a nib.
29 }
30 
31 - (void)didReceiveMemoryWarning {
32     [super didReceiveMemoryWarning];
33     // Dispose of any resources that can be recreated.
34 }
35 
36 - (void)addTimer
37 {
38     self.timer = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)];
39     [self.timer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
40 }
41 
42 - (void)removeTimer
43 {
44     [self.timer invalidate];
45     self.timer = nil;
46 }
47 
48 - (void)update
49 {
50     //跟新测试值
51     [self.recorder updateMeters];
52     float power = [self.recorder averagePowerForChannel:0];
53     if (power < -20) { //静音
54         self.silentDuration += self.timer.duration;
55         
56         if (self.silentDuration > 2) {
57             [self.recorder stop];
58         }
59     } else{ //说话
60         self.silentDuration = 0;
61     }
62 }
63 - (IBAction)startRecord {
64     NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
65     NSString *path = [doc stringByAppendingString:@"test.caf"];
66     NSURL *url = [NSURL fileURLWithPath:path];
67     
68     AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:url settings:nil error:nil];
69     //缓冲
70     [recorder prepareToRecord];
71     //录音
72     [recorder record];
73     
74     //开启分贝测量功能
75     recorder.meteringEnabled = YES;
76     [recorder averagePowerForChannel:0];
77     
78     self.recorder = recorder;
79 }
80 
81 - (IBAction)stopRecord {
82     [self.recorder stop];
83 }
84 @end

 

IOS-录音

标签:

原文地址:http://www.cnblogs.com/oc-bowen/p/5308014.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!