本文介绍的是实例编程iPhone 录音和播放,本文帮友们实现一个录音的效果,很有趣,我们一起来看!
实例编程iPhone 录音和播放是本文要介绍的内容,最近准备做一个关于录音和播放的项目!查了一些资料,很简单的做了一个,下面我就分享一下iPhone的录音和播放的使用心得。iPhone的录音和播放使用到了media层的内容,media层处于cocoa层之下,用到的很大一部分都是c语言的结构。
1、引入框架。
#import <AVFoundation/AVFoundation.h>
2、创建录音项。
- -(void)prepareToRecord
- {
- AVAudioSession*audioSession=[AVAudioSessionsharedInstance];
- NSError*err=nil;
- [audioSessionsetCategory:AVAudioSessionCategoryPlayAndRecorderror:&err];
- if(err){
- NSLog(@"audioSession:%@%d%@",[errdomain],[errcode],[[erruserInfo]description]);
- return;
- }
- [audioSessionsetActive:YESerror:&err];
- err=nil;
- if(err){
- NSLog(@"audioSession:%@%d%@",[errdomain],[errcode],[[erruserInfo]description]);
- return;
- }
- recordSetting=[[NSMutableDictionaryalloc]init];
- [recordSettingsetValue:[NSNumbernumberWithInt:kAudioFormatLinearPCM]forKey:AVFormatIDKey];
- [recordSettingsetValue:[NSNumbernumberWithFloat:44100.0]forKey:AVSampleRateKey];
- [recordSettingsetValue:[NSNumbernumberWithInt:2]forKey:AVNumberOfChannelsKey];
- [recordSettingsetValue:[NSNumbernumberWithInt:16]forKey:AVLinearPCMBitDepthKey];
- [recordSettingsetValue:[NSNumbernumberWithBool:NO]forKey:AVLinearPCMIsBigEndianKey];
- [recordSettingsetValue:[NSNumbernumberWithBool:NO]forKey:AVLinearPCMIsFloatKey];
- //Createanewdatedfile
- NSDate*now=[NSDatedateWithTimeIntervalSinceNow:0];
- NSString*caldate=[nowdescription];
- recorderFilePath=[[NSStringstringWithFormat:@"%@/%@.caf",DOCUMENTS_FOLDER,caldate]retain];
- NSURL*url=[NSURLfileURLWithPath:recorderFilePath];
- err=nil;
- recorder=[[AVAudioRecorderalloc]initWithURL:urlsettings:recordSettingerror:&err];
- if(!recorder){
- NSLog(@"recorder:%@%d%@",[errdomain],[errcode],[[erruserInfo]description]);
- UIAlertView*alert=
- [[UIAlertViewalloc]initWithTitle:@"Warning"
- message:[errlocalizedDescription]
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [alertshow];
- [alertrelease];
- return;
- }
- //preparetorecord
- [recordersetDelegate:self];
- [recorderprepareToRecord];
- recorder.meteringEnabled=YES;
- BOOLaudioHWAvailable=audioSession.inputIsAvailable;
- if(!audioHWAvailable){
- UIAlertView*cantRecordAlert=
- [[UIAlertViewalloc]initWithTitle:@"Warning"
- message:@"Audioinputhardwarenotavailable"
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [cantRecordAlertshow];
- [cantRecordAlertrelease];
- return;
- }
- }
以上这个方法就是创建了录音项,其中包括录音的路径和一些音频属性,但只是准备录音还没有录,如果要录的话还要加入以下的方法:
- (void)startrecorder
- {
- [recorderrecord];
- }
这样就在我们创建的路径下开始了录音。完成录音很简单:
- (void)stopRecording{
- [recorderstop];
- }
这里顺便提一下录音的代理方法:
- -(void)audioRecorderDidFinishRecording:(AVAudioRecorder*)aRecordersuccessfully:(BOOL)flag
- {
- NSLog(@"recordersuccessfully");
- UIAlertView*recorderSuccessful=[[UIAlertViewalloc]initWithTitle:@""message:@"录音成功"
- delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];
- [recorderSuccessfulshow];
- [recorderSuccessfulrelease];
- }
- -(void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder*)arecordererror:(NSError*)error
- {
- btnRecorder.enabled=NO;
- UIAlertView*recorderFailed=[[UIAlertViewalloc]initWithTitle:@""message:@"发生错误"
- delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil];
- [recorderFailedshow];
- [recorderFailedrelease];
- }
以上两个代理方法分别指定了录音的成功或失败。
录音中有一个的录音对象有一个averagePowerForChannel和peakPowerForChannel的属性分别为声音的最高振幅和平均振幅,有了他们就可以做一个动态的振幅的录音效果。
- -(void)updateAudioDisplay{
- if(isStart==NO){
- currentTimeLabel.text=@"--:--";
- }else{
- doublecurrentTime=recorder.currentTime;
- currentTimeLabel.text=[NSStringstringWithFormat:@"d:d",
- (int)currentTime/60,
- (int)currentTime%60];
- //START:code.RecordViewController.setlevelmeters
- [recorderupdateMeters];
- [leftLevelMetersetPower:[recorderaveragePowerForChannel:0]
- peak:[recorderpeakPowerForChannel:0]];
- if(!rightLevelMeter.hidden){
- [rightLevelMetersetPower:[recorderaveragePowerForChannel:1]
- peak:[recorderpeakPowerForChannel:1]];
- }
- //END:code.RecordViewController.setlevelmeters
- }
- }
- 以上就是录音相关的内容。
- 下面说一下播放的方法:
- voidSystemSoundsDemoCompletionProc(
- SystemSoundIDsoundID,
- void*clientData)
- {
- AudioServicesDisposeSystemSoundID(soundID);
- ((AudioRecorderPlayerAppDelegate*)clientData).statusLabel.text=@"Stopped";
- }
- -(void)playAudio
- {
- //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
- //createasystemsoundidfortheselectedrow
- SystemSoundIDsoundID;
- OSStatuserr=kAudioServicesNoError;
- //specialcase:vibrate//震动
- //soundID=kSystemSoundID_Vibrate;//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.vibratesystemsound"/>
- //findcorrespondingCAFfile
- //NSString*cafName=[NSStringstringWithFormat:@"%@",recorderFilePath];//<labelid="code.SystemSoundsDemo.
- SystemSoundsDemoViewController.createsystemsound.rowtonumberstring"/>
- NSURL*url=[NSURLfileURLWithPath:recorderFilePath];
- //NSString*cafPath=
- //[[NSBundlemainBundle]pathForResource:cafNameofType:@"caf"];//<labelid="code.SystemSoundsDemo.
- SystemSoundsDemoViewController.createsystemsound.findcafinbundle"/>
- //NSURL*cafURL=[NSURLfileURLWithPath:url];//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.
- createsystemsound.fileurlwithpath"/>
- err=AudioServicesCreateSystemSoundID((CFURLRef)url,&soundID);//<labelid="code.SystemSoundsDemo.
- SystemSoundsDemoViewController.createsystemsound.createsystemsound"/>
- //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound
- //START:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
- if(err==kAudioServicesNoError){
- //setupcallbackforsoundcompletion
- err=AudioServicesAddSystemSoundCompletion//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.
- createsystemsound.addcompletionproc"/>
- (soundID,//soundtomonitor
- NULL,//runloop(NULL==main)
- NULL,//runloopmode(NULL==default)
- SystemSoundsDemoCompletionProc,//callbackfunction//<labelid="code.SystemSoundsDemo.
- SystemSoundsDemoViewController.createsystemsound.completionprocroutine"/>
- self//datatoprovideoncallback
- );//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.addcompletionprocend"/>
- statusLabel.text=@"Playing";//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.setlabel"/>
- AudioServicesPlaySystemSound(soundID);//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.playsound"/>
- }
- if(err!=kAudioServicesNoError){//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockstart"/>
- CFErrorReferror=CFErrorCreate(NULL,kCFErrorDomainOSStatus,err,NULL);//<labelid="code.SystemSoundsDemo.
- SystemSoundsDemoViewController.createsystemsound.createcferror"/>
- NSString*errorDesc=(NSString*)CFErrorCopyDescription(error);//<labelid="code.SystemSoundsDemo.
- SystemSoundsDemoViewController.createsystemsound.copycferrordescription"/>
- UIAlertView*cantPlayAlert=
- [[UIAlertViewalloc]initWithTitle:@"CannotPlay:"
- message:errorDesc
- delegate:nil
- cancelButtonTitle:@"OK"
- otherButtonTitles:nil];
- [cantPlayAlertshow];
- [cantPlayAlertrelease];
- [errorDescrelease];//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerrordescription"/>
- CFRelease(error);//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.releaseerror"/>
- }//<labelid="code.SystemSoundsDemo.SystemSoundsDemoViewController.createsystemsound.errorblockend"/>
- //END:code.SystemSoundsDemo.SystemSoundsDemoViewController.registercompletionprocandplaysound
- }
通过以上的方法就应该能够实现播放,播放的时候也是可以加入振幅过程的,大家可以试试!这样一个iPhone录音机就做好了!哈哈
小结:实例编程iPhone 录音和播放的内容介绍完了,希望本文对你有所帮助。
转载请说明出处
知优网 » 实例编程iPhone 录音和播放(iphone 播放 录音)
知优网 » 实例编程iPhone 录音和播放(iphone 播放 录音)