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

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

实例编程iPhone 录音和播放(iphone 播放 录音)  iPhone 录音 第1张

1、引入框架。

#import <AVFoundation/AVFoundation.h>

2、创建录音项。

  1. -(void)prepareToRecord
  2. {
  3. AVAudioSession*audioSession=[AVAudioSessionsharedInstance];
  4. NSError*err=nil;
  5. [audioSessionsetCategory:AVAudioSessionCategoryPlayAndRecorderror:&err];
  6. if(err){
  7. NSLog(@"audioSession:%@%d%@",[errdomain],[errcode],[[erruserInfo]description]);
  8. return;
  9. }
  10. [audioSessionsetActive:YESerror:&err];
  11. err=nil;
  12. if(err){
  13. NSLog(@"audioSession:%@%d%@",[errdomain],[errcode],[[erruserInfo]description]);
  14. return;
  15. }
  16. recordSetting=[[NSMutableDictionaryalloc]init];
  17. [recordSettingsetValue:[NSNumbernumberWithInt:kAudioFormatLinearPCM]forKey:AVFormatIDKey];
  18. [recordSettingsetValue:[NSNumbernumberWithFloat:44100.0]forKey:AVSampleRateKey];
  19. [recordSettingsetValue:[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];
  20. [recordSettingsetValue:[NSNumbernumberWithInt:16]forKey:AVLinearPCMBitDepthKey];
  21. [recordSettingsetValue:[NSNumbernumberWithBool:NO]forKey:AVLinearPCMIsBigEndianKey];
  22. [recordSettingsetValue:[NSNumbernumberWithBool:NO]forKey:AVLinearPCMIsFloatKey];
  23. //Createanewdatedfile
  24. NSDate*now=[NSDatedateWithTimeIntervalSinceNow:0];
  25. NSString*caldate=[nowdescription];
  26. recorderFilePath=[[NSStringstringWithFormat:@"%@/%@.caf",DOCUMENTS_FOLDER,caldate]retain];
  27. NSURL*url=[NSURLfileURLWithPath:recorderFilePath];
  28. err=nil;
  29. recorder=[[AVAudioRecorderalloc]initWithURL:urlsettings:recordSettingerror:&err];
  30. if(!recorder){
  31. NSLog(@"recorder:%@%d%@",[errdomain],[errcode],[[erruserInfo]description]);
  32. UIAlertView*alert=
  33. [[UIAlertViewalloc]initWithTitle:@"Warning"
  34. message:[errlocalizedDescription]
  35. delegate:nil
  36. cancelButtonTitle:@"OK"
  37. otherButtonTitles:nil];
  38. [alertshow];
  39. [alertrelease];
  40. return;
  41. }
  42. //preparetorecord
  43. [recordersetDelegate:self];
  44. [recorderprepareToRecord];
  45. recorder.meteringEnabled=YES;
  46. BOOLaudioHWAvailable=audioSession.inputIsAvailable;
  47. if(!audioHWAvailable){
  48. UIAlertView*cantRecordAlert=
  49. [[UIAlertViewalloc]initWithTitle:@"Warning"
  50. message:@"Audioinputhardwarenotavailable"
  51. delegate:nil
  52. cancelButtonTitle:@"OK"
  53. otherButtonTitles:nil];
  54. [cantRecordAlertshow];
  55. [cantRecordAlertrelease];
  56. return;
  57. }
  58. }

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

  1. (void)startrecorder
  2. {
  3. [recorderrecord];
  4. }

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

  1. (void)stopRecording{
  2. [recorderstop];
  3. }

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

  1. -(void)audioRecorderDidFinishRecording:(AVAudioRecorder*)aRecordersuccessfully:(BOOL)flag
  2. {
  3. NSLog(@"recordersuccessfully");
  4. UIAlertView*recorderSuccessful=[[UIAlertViewalloc]initWithTitle:@""message:@"录音成功"
  5. delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];
  6. [recorderSuccessfulshow];
  7. [recorderSuccessfulrelease];
  8. }
  9. -(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder*)arecordererror:(NSError*)error
  10. {
  11. btnRecorder.enabled=NO;
  12. UIAlertView*recorderFailed=[[UIAlertViewalloc]initWithTitle:@""message:@"发生错误"
  13. delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];
  14. [recorderFailedshow];
  15. [recorderFailedrelease];
  16. }

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

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

  1. -(void)updateAudioDisplay{
  2. if(isStart==NO){
  3. currentTimeLabel.text=@"--:--";
  4. }else{
  5. doublecurrentTime=recorder.currentTime;
  6. currentTimeLabel.text=[NSStringstringWithFormat:@"d:d",
  7. (int)currentTime/60,
  8. (int)currentTime%60];
  9. //START:code.RecordViewController.setlevelmeters
  10. [recorderupdateMeters];
  11. [leftLevelMetersetPower:[recorderaveragePowerForChannel:0]
  12. peak:[recorderpeakPowerForChannel:0]];
  13. if(!rightLevelMeter.hidden){
  14. [rightLevelMetersetPower:[recorderaveragePowerForChannel:1]
  15. peak:[recorderpeakPowerForChannel:1]];
  16. }
  17. //END:code.RecordViewController.setlevelmeters
  18. }
  19. }
  20. 以上就是录音相关的内容。
  21. 下面说一下播放的方法:
  22. voidSystemSoundsDemoCompletionProc(
  23. SystemSoundIDsoundID,
  24. void*clientData)
  25. {
  26. AudioServicesDisposeSystemSoundID(soundID);
  27. ((AudioRecorderPlayerAppDelegate*)clientData).statusLabel.text=@"Stopped";
  28. }
  29. -(void)playAudio
  30. {
  31. //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
  32. //createasystemsoundidfortheselectedrow
  33. SystemSoundIDsoundID;
  34. OSStatuserr=kAudioServicesNoError;
  35. //specialcase:vibrate//震动
  36. //soundID=kSystemSoundID_Vibrate;//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.vibratesystemsound"/>
  37. //findcorrespondingCAFfile
  38. //NSString*cafName=[NSStringstringWithFormat:@"%@",recorderFilePath];//<labelid="code.SystemSoundsDemo.
  39. SystemSoundsDemoViewController.createsystemsound.rowtonumberstring"/>
  40. NSURL*url=[NSURLfileURLWithPath:recorderFilePath];
  41. //NSString*cafPath=
  42. //[[NSBundlemainBundle]pathForResource:cafNameofType:@"caf"];//<labelid="code.SystemSoundsDemo.
  43. SystemSoundsDemoViewController.createsystemsound.findcafinbundle"/>
  44. //NSURL*cafURL=[NSURLfileURLWithPath:url];//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.
  45. createsystemsound.fileurlwithpath"/>
  46. err=AudioServicesCreateSystemSoundID((CFURLRef)url,&soundID);//<labelid="code.SystemSoundsDemo.
  47. SystemSoundsDemoViewController.createsystemsound.createsystemsound"/>
  48. //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
  49. //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
  50. if(err==kAudioServicesNoError){
  51. //setupcallbackforsoundcompletion
  52. err=AudioServicesAddSystemSoundCompletion//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.
  53. createsystemsound.addcompletionproc"/>
  54. (soundID,//soundtomonitor
  55. NULL,//runloop(NULL==main)
  56. NULL,//runloopmode(NULL==default)
  57. SystemSoundsDemoCompletionProc,//callbackfunction//<labelid="code.SystemSoundsDemo.
  58. SystemSoundsDemoViewController.createsystemsound.completionprocroutine"/>
  59. self//datatoprovideoncallback
  60. );//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionprocend"/>
  61. statusLabel.text=@"Playing";//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.setlabel"/>
  62. AudioServicesPlaySystemSound(soundID);//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.playsound"/>
  63. }
  64. if(err!=kAudioServicesNoError){//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockstart"/>
  65. CFErrorReferror=CFErrorCreate(NULL,kCFErrorDomainOSStatus,err,NULL);//<labelid="code.SystemSoundsDemo.
  66. SystemSoundsDemoViewController.createsystemsound.createcferror"/>
  67. NSString*errorDesc=(NSString*)CFErrorCopyDescription(error);//<labelid="code.SystemSoundsDemo.
  68. SystemSoundsDemoViewController.createsystemsound.copycferrordescription"/>
  69. UIAlertView*cantPlayAlert=
  70. [[UIAlertViewalloc]initWithTitle:@"CannotPlay:"
  71. message:errorDesc
  72. delegate:nil
  73. cancelButtonTitle:@"OK"
  74. otherButtonTitles:nil];
  75. [cantPlayAlertshow];
  76. [cantPlayAlertrelease];
  77. [errorDescrelease];//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerrordescription"/>
  78. CFRelease(error);//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerror"/>
  79. }//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockend"/>
  80. //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
  81. }

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

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

转载请说明出处
知优网 » 实例编程iPhone 录音和播放(iphone 播放 录音)

发表评论

您需要后才能发表评论