ios录音与播放

转载自:http://blog.csdn.net/xj2014/article/details/20318241


1、AVAudioSession 的使用

AVAudioSession是一个单例模式。在IOS7以前可以不用设置,在IOS7上不设置AVAudioSession则不可以录音。 

一、设置AVAudioSession的类别(部分)及开启音频会话

类别(Category)作用
AVAudioSessionCategoryPlayback后台播放
AVAudioSessionCategoryRecord录音
AVAudioSessionCategoryPlayAndRecord后台播放及录音

    


具体代码如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //录音权限设置  
  2. AVAudioSession *audioSession = [AVAudioSession sharedInstance];  
  3. //设置类别只支持录音  
  4. [audioSession setCategory:AVAudioSessionCategoryRecord error:nil];  
  5. //启动音频会话管理,此时会阻断后台音乐的播放  
  6. [audioSession setActive:YES error:nil];  
二、在录音或播放结束后,要关闭音频会话,来延续后台音乐的播放

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AVAudioSession *audioSession = [AVAudioSession sharedInstance];  
  2. [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];  
  3. [audioSession setActive:NO error:nil];  

三、要想启用其他程序的后台音乐播放,则要用如下设置

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. AVAudioSession *audioSession = [AVAudioSession sharedInstance];  
  2. [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];  
  3. [audioSession setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:nil];  

2、AVAudioRecorder的基本使用

一、设置参数

Key作用
AVFormatIDKey录音格式kAudioFormatMPEG4AAC、kAudioFormatLinearPCM...
AVSampleRateKey录音采样率
影响音频的质量
8000、44100、96000
AVNumberOfChannelsKey录音通道数1或2
AVLinearPCMBitDepthKey线性采样位数8、16、24、32
AVEncoderAudioQualityKey录音质量
AVAudioQualityMin、AVAudioQualityLow 、
AVAudioQualityMedium、AVAudioQualityHigh、
AVAudioQualityMax

二、保存路径的Url设置

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //CFUUID每次都会产生一个唯一号  
  2. CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);  
  3. NSString *cfuuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));  
  4. NSString *catchPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];  
  5. NSString *audioRecordFilePath=[catchPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.AAC", cfuuidString]];  
  6. NSURL *url=[NSURL fileURLWithPath:audioRecordFilePath];  

三、AVAudioRecorder初始化

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSError *error=nil;  
  2. AVAudioRecorder *recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];  

四、所有代码如下:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //录音参数设置设置  
  2. NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];  
  3. //设置录音格式  
  4. [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];  
  5. //设置录音采样率  
  6. [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];  
  7. //录音通道数  
  8. [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];  
  9. //线性采样位数  
  10. [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];  
  11. //录音的质量  
  12. [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];  
  13. //录音文件保存的URL  
  14. CFUUIDRef cfuuid = CFUUIDCreate(kCFAllocatorDefault);  
  15. NSString *cfuuidString = (NSString*)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));  
  16. NSString *catchPath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];  
  17. NSString *audioRecordFilePath=[catchPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.AAC", cfuuidString]];  
  18. NSURL *url = [NSURL fileURLWithPath:audioRecordFilePath];  
  19. NSError *error=nil;  
  20. //初始化AVAudioRecorder  
  21. _recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];  
  22. if (error != nil) {  
  23.     //NSLog(@"初始化录音Error: %@",error);  
  24. }else{  
  25.    if ([_recorder prepareToRecord]) {  
  26.        //录音最长时间设置  
  27.        [_recorder recordForDuration:20];  
  28.        //委托事件  
  29.        _recorder.delegate=self;  
  30.        [_recorder record];  
  31.        //开启音量检测  
  32.        _recorder.meteringEnabled = YES;  
  33.        //开启定时器,音量监测  
  34.        _timer=[NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(volumeMeters:) userInfo:nil repeats:YES];  
  35.     }  
  36. }  
  37. #pragma mark 实时监测音量变化 定时器任务  
  38. - (void)volumeMeters:(NSTimer *)timer  
  39. {  
  40.     //刷新音量数据  
  41.     [_recorder updateMeters];  
  42.     double lowPassResults = pow(10, (0.05 * [_recorder peakPowerForChannel:0]));  
  43.     if (0<lowPassResults<=0.14) {  
  44.           
  45.     }else if (0.14<lowPassResults<=0.28) {  
  46.           
  47.     }else if (0.28<lowPassResults<=0.42) {  
  48.   
  49.     }else if (0.42<lowPassResults<=0.56) {  
  50.   
  51.     }else if (0.56<lowPassResults<=0.7) {  
  52.   
  53.     }else if (0.7<lowPassResults<=0.84) {  
  54.   
  55.     }else if (0.84<lowPassResults<=0.98) {  
  56.   
  57.     }else {  
  58.   
  59.     }  
  60. }  
  61.   
  62. //AVAudioRecorder委托事件  
  63. - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag  
  64. {  
  65.   //录音结束  
  66. }  
  67. - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error  
  68. {  
  69.   //录音编码错误  
  70. }  

3、AVAudioPlayer的使用

主要用于音频文件的播放,它主要有两个初始化方法:initWithData与initWithContentsOfURL。两个一般都可以使用,但在使用initWithContentsOfURL时要注意传入文件的文件名的格式,稍有不同,则无法播放,如:aac文件,如果后缀名为大写AAC,则无法播放。 

[objc]  view plain copy
  1. //initWithContentsOfURL  
  2. NSURL *urlAudio=[NSURL fileURLWithPath:audioPath];  
  3. AVAudioPlayer *_player=[[AVAudioPlayer alloc]initWithContentsOfURL:urlAudio error:nil];  
  4. //initWithData  
  5. NSData *dataAudio=[NSData dataWithContentsOfFile:audioPath];  
  6. NSError *error=nil;  
  7. AVAudioPlayer *_player = [[AVAudioPlayer alloc]initWithData:dataAudio error:&error];  
  8. //属性设置  
  9. [_player prepareToPlay];        //准备播放  
  10. [_player play];                 //播放  
  11. [_player pause];                //暂停播放  
  12. [_player stop];                 //停止播放  
  13. _player.duration;               //播放持续时间,只读  
  14. _player.volume=0.8;             //设置音量大小  
  15. _player.currentTime=15.0;       //设置当前播放时间  
  16. _player.numberOfLoops=3;        //循环播放时间  
  17. _player.delegate=self;          //委托事件  
  18.   
  19. //AVAudioPlayer委托事件  
  20. - (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag  
  21. {  
  22.   //音频文件播放结束  
  23. }  
  24. - (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error  
  25. {  
  26.   //音频文件解码错误  
  27. }  

注:录音类AVAudioRecorder最好设置为全局变量。如果为局部变量,当销毁掉时将结束录音

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值