录音

来源:互联网 发布:网络封包 编辑:程序博客网 时间:2024/04/27 18:51

简单实现录音功能 

声明全局成员变量

@property(nonatomic,strong)AVAudioRecorder *recorder ;

@property (nonatomic,strong) AVAudioPlayer * audioPlayer;

@property (nonatomic,strong) CADisplayLink *link;

@property (nonatomic,assign) double slientDuration;


- (CADisplayLink *)link

{

    if (!_link) {

        self.link = [CADisplayLinkdisplayLinkWithTarget:selfselector:@selector(update)];

    }

    return_link;

}

//开始录音

- (IBAction)startRecording:(id)sender {

    

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject] stringByAppendingString:@"tesst.caf"];

    NSURL *url = [NSURLfileURLWithPath:path];

    

    NSMutableDictionary *setting = [NSMutableDictionarydictionary];

    

    //音频格式

    setting[AVFormatIDKey] =@(kAudioFormatAppleIMA4);

    //音频采样率

    setting[AVSampleRateKey]=@(8000.0);

    //音频通道数

    setting[AVNumberOfChannelsKey] =@(1);

    //线性音频的位深度

    setting[AVLinearPCMBitDepthKey] =@(8);

    

//    创建录音器

    AVAudioRecorder *recorder = [[AVAudioRecorderalloc] initWithURL:urlsettings:setting error:nil];

    

    //允许测量分贝

    recorder.meteringEnabled =YES;

    //缓冲

    [recorder prepareToRecord];

    //录音

    [recorder record];

    self.recorder = recorder;

}


- (IBAction)stopRecording:(id)sender {

   

    [self.recorderstop];

}

   

//真机中文件读取不到  可以在模拟器中取到声音文件

- (IBAction)playRecording:(id)sender {

    

    //加载音乐文件

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject] stringByAppendingString:@"tesst.caf"];

    

//    NSURL *url = [[NSBundle mainBundle] URLForResource:path withExtension:nil];

    

    NSData *data = [[NSFileManagerdefaultManager] contentsAtPath:path];

    

    NSError *error =nil;

    _audioPlayer = [[AVAudioPlayeralloc] initWithData:dataerror:&error];

    

//    _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

    

    NSLog(@"%@", error);

    

    //缓冲

    [_audioPlayerprepareToPlay];

    [_audioPlayerplay];


}




0 0
原创粉丝点击