实例编程iPhone 录音和播放

移动开发 iOS
本文介绍的是实例编程iPhone 录音和播放,本文帮友们实现一个录音的效果,很有趣,我们一起来看!

实例编程iPhone 录音播放是本文要介绍的内容,最近准备做一个关于录音播放的项目!查了一些资料,很简单的做了一个,下面我就分享一下iPhone录音播放的使用心得。iPhone的录音和播放使用到了media层的内容,media层处于cocoa层之下,用到的很大一部分都是c语言的结构。

1、引入框架。

#import <AVFoundation/AVFoundation.h>

2、创建录音项。

  1. - (void) prepareToRecord  
  2.  
  3. {  
  4.  
  5. AVAudioSession *audioSession = [AVAudioSession sharedInstance];  
  6.  
  7. NSError *err = nil;  
  8.  
  9. [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];  
  10.  
  11. if(err){  
  12.  
  13.         NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);  
  14.  
  15.         return;  
  16.  
  17. }  
  18.  
  19. [audioSession setActive:YES error:&err];  
  20.  
  21. err = nil;  
  22.  
  23. if(err){  
  24.  
  25.         NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);  
  26.  
  27.         return;  
  28.  
  29. }  
  30.  
  31. recordSetting = [[NSMutableDictionary alloc] init];  
  32.  
  33. [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];  
  34.  
  35. [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];   
  36.  
  37. [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];  
  38.  
  39. [recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];  
  40.  
  41. [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];  
  42.  
  43. [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];  
  44.  
  45. // Create a new dated file  
  46. NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];  
  47. NSString *caldate = [now description];  
  48. recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];  
  49. NSURL *url = [NSURL fileURLWithPath:recorderFilePath];  
  50. err = nil;  
  51. recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];  
  52. if(!recorder){  
  53.         NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);  
  54.         UIAlertView *alert =  
  55.         [[UIAlertView alloc] initWithTitle: @"Warning"  
  56.   message: [err localizedDescription]  
  57.   delegate: nil  
  58. cancelButtonTitle:@"OK"  
  59. otherButtonTitles:nil];  
  60.         [alert show];  
  61.         [alert release];  
  62.         return;  
  63. }  
  64. //prepare to record  
  65. [recorder setDelegate:self];  
  66. [recorder prepareToRecord];  
  67. recorder.meteringEnabled = YES;  
  68. BOOL audioHWAvailable = audioSession.inputIsAvailable;  
  69. if (! audioHWAvailable) {  
  70.         UIAlertView *cantRecordAlert =  
  71.         [[UIAlertView alloc] initWithTitle: @"Warning"  
  72.   message: @"Audio input hardware not available"  
  73.   delegate: nil  
  74. cancelButtonTitle:@"OK"  
  75. otherButtonTitles:nil];  
  76.         [cantRecordAlert show];  
  77.         [cantRecordAlert release];   
  78.         return;  
  79. }  

以上这个方法就是创建了录音项,其中包括录音的路径和一些音频属性,但只是准备录音还没有录,如果要录的话还要加入以下的方法:

  1. (void)startrecorder  
  2. {  
  3. [recorder record];  

这样就在我们创建的路径下开始了录音。完成录音很简单:

  1. (void) stopRecording{  
  2. [recorder stop];  

这里顺便提一下录音的代理方法:

  1. - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag  
  2. {  
  3. NSLog(@"recorder successfully");  
  4. UIAlertView *recorderSuccessful = [[UIAlertView alloc] initWithTitle:@"" message:@"录音成功"
  5. delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  6. [recorderSuccessful show];  
  7. [recorderSuccessful release];  
  8. }  
  9.  
  10. - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)arecorder error:(NSError *)error  
  11. {  
  12. btnRecorder.enabled = NO;  
  13. UIAlertView *recorderFailed = [[UIAlertView alloc] initWithTitle:@"" message:@"发生错误"
  14. delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  
  15. [recorderFailed show];  
  16. [recorderFailed release];  

以上两个代理方法分别指定了录音的成功或失败。

录音中有一个的录音对象有一个averagePowerForChannel和peakPowerForChannel的属性分别为声音的最高振幅和平均振幅,有了他们就可以做一个动态的振幅的录音效果。

  1. - (void) updateAudioDisplay {  
  2.  
  3. if (isStart == NO) {  
  4.  
  5. currentTimeLabel.text = @"--:--";  
  6.  
  7. } else {  
  8.  
  9. double currentTime = recorder.currentTime;  
  10.  
  11. currentTimeLabel.text = [NSString stringWithFormat: @"d:d",  
  12.  
  13. (int) currentTime/60,  
  14.  
  15. (int) currentTime%60];  
  16.  
  17. //START:code.RecordViewController.setlevelmeters  
  18.  
  19. [recorder updateMeters];  
  20.  
  21. [leftLevelMeter setPower: [recorder averagePowerForChannel:0]  
  22.  
  23. peak: [recorder peakPowerForChannel: 0]];  
  24.  
  25. if (! rightLevelMeter.hidden) {  
  26.  
  27. [rightLevelMeter setPower: [recorder averagePowerForChannel:1]  
  28.  
  29. peak: [recorder peakPowerForChannel: 1]];  
  30.  
  31. }  
  32.  
  33. //END:code.RecordViewController.setlevelmeters  
  34.  
  35. }  
  36.  
  37. }  
  38.  
  39. 以上就是录音相关的内容。  
  40.  
  41. 下面说一下播放的方法:  
  42.  
  43. void SystemSoundsDemoCompletionProc (  
  44. SystemSoundID  soundID,  
  45. void           *clientData)  
  46. {  
  47. AudioServicesDisposeSystemSoundID (soundID);  
  48. ((AudioRecorderPlayerAppDelegate*)clientData).statusLabel.text = @"Stopped";  
  49. }  
  50. -(void)playAudio  
  51. {  
  52. //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound  
  53. // create a system sound id for the selected row  
  54. SystemSoundID soundID;  
  55. OSStatus err = kAudioServicesNoError;  
  56. // special case: vibrate//震动  
  57. //soundID = kSystemSoundID_Vibrate; //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.vibratesystemsound"/> 
  58.  
  59. // find corresponding CAF file  
  60.  
  61. //NSString *cafName = [NSString stringWithFormat: @"%@",recorderFilePath]; //<label id="code.SystemSoundsDemo.
  62. SystemSoundsDemoViewController.createsystemsound.rowtonumberstring"/> 
  63.  
  64. NSURL *url = [NSURL fileURLWithPath:recorderFilePath];  
  65. //NSString *cafPath =   
  66. //[[NSBundle mainBundle] pathForResource:cafName ofType:@"caf"]; //<label id="code.SystemSoundsDemo.
  67. SystemSoundsDemoViewController.createsystemsound.findcafinbundle"/> 
  68. //NSURL *cafURL = [NSURL fileURLWithPath:url]; //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.
  69. createsystemsound.fileurlwithpath"/> 
  70. err = AudioServicesCreateSystemSoundID((CFURLRef) url, &soundID); //<label id="code.SystemSoundsDemo.
  71. SystemSoundsDemoViewController.createsystemsound.createsystemsound"/> 
  72. //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound  
  73. //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound  
  74. if (err == kAudioServicesNoError) {  
  75.  
  76. // set up callback for sound completion  
  77. err = AudioServicesAddSystemSoundCompletion //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.
  78. createsystemsound.addcompletionproc"/> 
  79. (soundID,// sound to monitor  
  80. NULL,// run loop (NULL==main)  
  81. NULL,// run loop mode (NULL==default)  
  82. SystemSoundsDemoCompletionProc, // callback function //<label id="code.SystemSoundsDemo.
  83. SystemSoundsDemoViewController.createsystemsound.completionprocroutine"/> 
  84. self // data to provide on callback  
  85. ); //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionprocend"/> 
  86. statusLabel.text = @"Playing"; //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.setlabel"/> 
  87. AudioServicesPlaySystemSound (soundID); //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.playsound"/> 
  88. }  
  89. if (err != kAudioServicesNoError) { //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockstart"/> 
  90. CFErrorRef error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, err, NULL); //<label id="code.SystemSoundsDemo.
  91. SystemSoundsDemoViewController.createsystemsound.createcferror"/> 
  92. NSString *errorDesc = (NSString*) CFErrorCopyDescription (error); //<label id="code.SystemSoundsDemo.
  93. SystemSoundsDemoViewController.createsystemsound.copycferrordescription"/> 
  94. UIAlertView *cantPlayAlert =  
  95. [[UIAlertView alloc] initWithTitle:@"Cannot Play:"  
  96.   message: errorDesc  
  97.   delegate:nil  
  98. cancelButtonTitle:@"OK"  
  99. otherButtonTitles:nil];  
  100. [cantPlayAlert show];  
  101. [cantPlayAlert release];   
  102. [errorDesc release]; //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerrordescription"/> 
  103. CFRelease (error); //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerror"/> 
  104. } //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockend"/> 
  105. //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound  

通过以上的方法就应该能够实现播放,播放的时候也是可以加入振幅过程的,大家可以试试!这样一个iPhone录音机就做好了!哈哈

小结:实例编程iPhone 录音和播放的内容介绍完了,希望本文对你有所帮助。

责任编辑:zhaolei 来源: 博客园
相关推荐

2021-07-09 09:24:41

鸿蒙HarmonyOS应用

2011-07-26 15:56:53

iPhone 游戏 启动画面

2011-08-18 10:32:13

iPhone编程视图

2011-07-28 14:19:12

iPhone 网络编程 聊天程序

2011-07-26 11:08:23

iOS 录像 录音

2016-12-21 16:42:15

androidmediaplayer

2011-08-10 15:58:58

iPhone视频

2011-07-25 18:02:51

iPhone LibFetion 移植

2012-06-21 09:28:47

jQuery

2009-07-09 00:25:00

ScalaSet类Map类

2009-07-09 00:25:00

ScalaListTuple

2011-08-08 16:56:44

iPhone 字符处理 视图

2011-08-02 16:58:15

iPhone AVAudioPla 音频播放

2011-07-20 16:21:20

iPhone 视频 播放器

2011-08-17 14:57:31

iPhone应用视频播放

2011-07-27 09:50:31

iPhone AVAudioPla 音频

2011-08-08 18:19:09

iPhone音频播放

2011-07-08 20:32:57

iPhone midi

2011-07-21 16:48:19

iPhone 游戏

2011-07-22 15:59:15

iPhone 声音 文件
点赞
收藏

51CTO技术栈公众号