芜湖窦德长简历:实例编程iPhone 录音和播放

来源:百度文库 编辑:偶看新闻 时间:2024/06/03 03:46:40

实例编程iPhone 录音和播放

2011-07-18 15:32 佚名 博客园 我要评论(0) 字号:T | T

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

AD:


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

    1、引入框架。

    #import

    2、创建录音项。

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

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

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

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

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

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

    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. - (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)arecorder error:(NSError *)error
    10. {
    11. btnRecorder.enabled = NO;
    12. UIAlertView *recorderFailed = [[UIAlertView alloc] initWithTitle:@"" message:@"发生错误"
    13. delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    14. [recorderFailed show];
    15. [recorderFailed release];
    16. }

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

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

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

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

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