`
sinaier
  • 浏览: 34936 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

实例编程iPhone 录音和播放(收藏)

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

1、引入框架。

#import <AVFoundation/AVFoundation.h>

2、创建录音项。
- (void) prepareToRecord
   {
   AVAudioSession *audioSession = [AVAudioSession sharedInstance];
   NSError *err = nil;
   [audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
   if(err){
   NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
   return;
   }
   [audioSession setActive:YES error:&err];
   err = nil;
   if(err){
   NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
   return;
   }
   recordSetting = [[NSMutableDictionary alloc] init];
   [recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
   [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
   [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
   [recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
   [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
   [recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];
   // Create a new dated file  NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
   NSString *caldate = [now description];
   recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];
   NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
   err = nil;
   recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
   if(!recorder){
   NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
   UIAlertView *alert =
   [[UIAlertView alloc] initWithTitle: @"Warning"
   message: [err localizedDescription]
   delegate: nil  cancelButtonTitle:@"OK"  otherButtonTitles:nil];
   [alert show];
   [alert release];
   return;
   }
   //prepare to record
   [recorder setDelegate:self];
   [recorder prepareToRecord];
   recorder.meteringEnabled = YES;
   BOOL audioHWAvailable = audioSession.inputIsAvailable;
   if (! audioHWAvailable) {
   UIAlertView *cantRecordAlert = 
   [[UIAlertView alloc] initWithTitle: @"Warning"
   message: @"Audio input hardware not available"
   delegate: nil  cancelButtonTitle:@"OK"  otherButtonTitles:nil];
   [cantRecordAlert show];   
   [cantRecordAlert release];
   return;  }
   }
以上这个方法就是创建了录音项,其中包括录音的路径和一些音频属性,但只是准备录音还没有录,如果要录的话还要加入以下的方法:
(void)startrecorder  {
  [recorder record];
  }
这样就在我们创建的路径下开始了录音。完成录音很简单:
(void) stopRecording{
  [recorder stop];
  }
这里顺便提一下录音的代理方法:
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag  {
NSLog(@"recorder successfully"); 
UIAlertView *recorderSuccessful =
[[UIAlertView alloc] initWithTitle:@""
message:@"录音成功"delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[recorderSuccessful show];
[recorderSuccessful release];

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)arecorder error:(NSError *)error  { 
btnRecorder.enabled = NO;
UIAlertView *recorderFailed =
[[UIAlertView alloc] initWithTitle:@"" message:@"发生错误"
delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[recorderFailed show];
[recorderFailed release];
}
以上两个代理方法分别指定了录音的成功或失败。

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

- (void) updateAudioDisplay {
  if (isStart == NO) {
  currentTimeLabel.text = @"--:--";
  }
  else {
  double currentTime = recorder.currentTime;
  currentTimeLabel.text = [NSString stringWithFormat: @"d:d",
  (int) currentTime/60,   (int) currentTime%60];
  //START:code.RecordViewController.setlevelmeters
  [recorder updateMeters];  
  [leftLevelMeter setPower: [recorder averagePowerForChannel:0] peak: [recorder peakPowerForChannel: 0]];
  if (! rightLevelMeter.hidden) {
  [rightLevelMeter setPower: [recorder averagePowerForChannel:1]   peak: [recorder peakPowerForChannel: 1]];
  }
  //END:code.RecordViewController.setlevelmeters
  }
  } 
  以上就是录音相关的内容。
  下面说一下播放的方法:
  void SystemSoundsDemoCompletionProc (  SystemSoundID  soundID,  void           *clientData)  {
  AudioServicesDisposeSystemSoundID (soundID); 
  ((AudioRecorderPlayerAppDelegate*)clientData).statusLabel.text = @"Stopped";
  }
  -(void)playAudio  {
  //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
  // create a system sound id for the selected row  SystemSoundID soundID;
  OSStatus err = kAudioServicesNoError;
  // special case: vibrate
  //震动
  //soundID = kSystemSoundID_Vibrate;
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.vibratesystemsound"/>
  // find corresponding CAF file
  //NSString *cafName = [NSString stringWithFormat: @"%@",recorderFilePath];
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.rowtonumberstring"/>
  NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
  //NSString *cafPath = 
  //[[NSBundle mainBundle] pathForResource:cafName ofType:@"caf"];
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.findcafinbundle"/>
  //NSURL *cafURL = [NSURL fileURLWithPath:url];
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.fileurlwithpath"/> err = AudioServicesCreateSystemSoundID((CFURLRef) url, &soundID);
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.createsystemsound"/>
  //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
  //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
  if (err == kAudioServicesNoError) { 
  // set up callback for sound completion  err = AudioServicesAddSystemSoundCompletion
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionproc"/>(soundID,
  // sound to monitor  NULL,
  // run loop (NULL==main)  NULL,
  // run loop mode (NULL==default)  SystemSoundsDemoCompletionProc,
  // callback function
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.completionprocroutine"/> self
  // data to provide on callback  );
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionprocend"/> statusLabel.text = @"Playing";
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.setlabel"/> AudioServicesPlaySystemSound (soundID);
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.playsound"/>
  }
  if (err != kAudioServicesNoError) {
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockstart"/>
  CFErrorRef error = CFErrorCreate(NULL, kCFErrorDomainOSStatus, err, NULL);
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.createcferror"/>
  NSString *errorDesc = (NSString*) CFErrorCopyDescription (error);
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.copycferrordescription"/>
  UIAlertView *cantPlayAlert =  [[UIAlertView alloc] initWithTitle:@"Cannot Play:"    message: errorDesc    delegate:nil  cancelButtonTitle:@"OK"  otherButtonTitles:nil];  [cantPlayAlert show];
  [cantPlayAlert release];
  [errorDesc release];
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerrordescription"/>
  CFRelease (error);
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerror"/>
  }
  //<label id="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockend"/>
  //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
  }
通过以上的方法就应该能够实现播放,播放的时候也是可以加入振幅过程的,大家可以试试!这样一个iPhone录音机就做好了
分享到:
评论
1 楼 yulanfeiyang 2012-07-30  

相关推荐

    iphone 开发播放歌曲文件并录制 边播边录

    为了实现边播边录,需要确保录音和播放的操作在时间上同步。 3. **多线程编程**:因为音频播放和录制可能需要较长的时间,所以通常在后台线程执行,以避免阻塞主线程。可以使用GCD的`dispatch_async`或`Operation...

    iphone 官方的例子

    6. **SpeakHere.zip**:这可能是一个语音录音和回放的应用,涉及到`AVFoundation`框架,特别是`AVAudioRecorder`和`AVAudioPlayer`的使用,用于录制和播放音频。 7. **SQLiteBooks.zip**:这个示例可能会讲解如何...

    iphone开发基础教程配套资料

    通过对Objective-C语言的学习、Xcode工具的使用、UIKit和Core Data框架的理解以及多线程与网络编程等核心技术的掌握,读者可以建立起坚实的iPhone开发基础。同时,通过具体的实践案例分析,本书还能够帮助读者将理论...

    iPhone应用开发指南 英文高清带书签完全版

    3. **编程语言与框架**:介绍了Objective-C和Swift两种主流的开发语言及其特点,同时提到了Cocoa Touch框架的重要性。 4. **用户界面设计**:讲解了如何使用Interface Builder来构建美观且易用的用户界面。 5. **...

    sams_teach_yourself_iphone_application_development_in_24_hours_2nd_edition

    2nd Edition》,即《24小时学会iPhone应用开发第二版》,由John Ray撰写,旨在为iOS开发初学者提供一个简单易懂的教学教程,通过大量实例和代码来帮助读者快速掌握iOS应用开发的基础知识和技能。 首先,书中涉及的...

    RecordingTranscoding Xcode iOS 工程

    总之,"RecordingTranscoding Xcode iOS 工程"是一个涵盖了iOS音频处理全链路的示例,包括录音、转码和播放。通过学习这个项目,开发者可以深入了解`AVFoundation`框架在音频处理中的应用,以及如何在Xcode中构建和...

    AudioJackDataCollector:通过 iPhone 音频插Kong记录数据,以频率表示的数据

    在这个项目中,我们主要关注的是其录音和频率分析的功能。 1. **设置音频会话** 在开始收集音频数据之前,需要配置一个音频会话(AVAudioSession),以确定应用程序如何与其他音频源交互。设置正确的Category(如...

    iOS.5.Recipes

    根据版权页上的信息,本书的所有权利均受到保护,未经版权所有者和出版社的书面许可,任何部分不得以任何形式或方式复制或传播,包括但不限于电子或机械方式,如复印、录音或任何信息存储和检索系统。 #### 内容...

    iOS中震动反馈(UIFeedbackGenerator)与系统震动详解

    它首次在Apple Watch中亮相,随后被应用于iPhone 6s和6s Plus,为Force Touch和3D Touch功能提供了支持。Taptic Engine能够根据不同的用户操作,如轻按、重压或滑动,提供不同程度和类型的振动反馈,从而丰富了用户...

    智游面试题10.27副本.pdf

    - **Core Audio**: 提供了音频处理功能,如录音、播放等。 - **OpenAL**: 开放式音频库,用于游戏和其他应用中的高效音频处理。 - **Media Library**: 提供了访问媒体文件的功能。 - **AVFoundation**: 提供多媒体...

    libmp3lame-ios

    4. API友好:提供了简洁的C语言接口,易于与其他编程语言(如Objective-C和Swift)交互。 二、libmp3lame-ios在iOS开发中的应用 1. 音频录制与编码:利用libmp3lame-ios,开发者可以将iOS设备的麦克风输入转换为高...

Global site tag (gtag.js) - Google Analytics