录音 播放 AVAudioSession AVAudioPlayer

//录音

-(void)tape{

AVAudioSession*session = [AVAudioSessionsharedInstance];

NSError*sessionError;

//AVAudioSessionCategoryPlayAndRecord用于录音和播放

[sessionsetCategory:AVAudioSessionCategoryPlayAndRecorderror:&sessionError];

if(session ==nil)

NSLog(@"Error creating session: %@", [sessionErrordescription]);

else

[sessionsetActive:YESerror:nil];

NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString*documentsDirectory=[pathsobjectAtIndex:0];//Documents目录

self.playName= [NSStringstringWithFormat:@"%@/play2.aac",documentsDirectory];

//录音设置

self.recorderSettingsDict=[[NSDictionaryalloc]initWithObjectsAndKeys:

[NSNumbernumberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,

[NSNumbernumberWithInt:44100.0],AVSampleRateKey,

[NSNumbernumberWithInt:2],AVNumberOfChannelsKey,

[NSNumbernumberWithInt:8],AVLinearPCMBitDepthKey,

[NSNumbernumberWithBool:NO],AVLinearPCMIsBigEndianKey,

[NSNumbernumberWithBool:NO],AVLinearPCMIsFloatKey,

nil];

NSError*error =nil;

//必须真机上测试,模拟器上可能会崩溃

self.recordering= [[AVAudioRecorderalloc]initWithURL:[NSURLURLWithString:self.playName]

settings:self.recorderSettingsDict

error:&error];

if(self.recordering) {

//打开音量检测

self.recordering.meteringEnabled=YES;

//创建文件准备录音

[self.recorderingprepareToRecord];

//开始录音

[self.recorderingrecord];

//启动定时器

self.timer= [NSTimerscheduledTimerWithTimeInterval:0.01target:selfselector:@selector(levelTimer:)userInfo:nilrepeats:YES];

[[NSRunLoopcurrentRunLoop]addTimer:self.timerforMode:NSRunLoopCommonModes];

}

}

//播放

- (IBAction)playAction:(id)sender {

if(self.playName.length==0){

UIAlertView* alertView = [[UIAlertViewalloc]initWithTitle:@"⚠️"message:@"请先录音"delegate:nilcancelButtonTitle:@"确定"otherButtonTitles:nil];

[alertViewshow];

}else{

NSURL*soundUrl = [NSURLfileURLWithPath:self.playName];

//初始化播放器的时候如下设置

UInt32sessionCategory =kAudioSessionCategory_MediaPlayback;

AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,

sizeof(sessionCategory),

&sessionCategory);

UInt32audioRouteOverride =kAudioSessionOverrideAudioRoute_Speaker;

AudioSessionSetProperty(kAudioSessionProperty_OverrideAudioRoute,

sizeof(audioRouteOverride),

&audioRouteOverride);

AVAudioSession*audioSession = [AVAudioSessionsharedInstance];

//默认情况下扬声器播放

[audioSessionsetCategory:AVAudioSessionCategoryPlaybackerror:nil];

[audioSessionsetActive:YESerror:nil];

NSError*playerError;

self.player= [[AVAudioPlayeralloc]initWithContentsOfURL:soundUrlerror:&playerError];

self.player.volume=1;

self.player.meteringEnabled=YES;

self.player.delegate=self;

if(self.player==nil)

{

NSLog(@"ERror creating player: %@", [playerErrordescription]);

}

[selfhandleNotification:YES];

[self.playerprepareToPlay];

[self.playerplay];

}

#pragma mark -监听听筒or扬声器

- (void) handleNotification:(BOOL)state

{

[[UIDevicecurrentDevice]setProximityMonitoringEnabled:state];//建议在播放之前设置yes,播放结束设置NO,这个功能是开启红外感应

if(state)//添加监听

[[NSNotificationCenterdefaultCenter]addObserver:self

selector:@selector(sensorStateChange:)name:@"UIDeviceProximityStateDidChangeNotification"

object:nil];

else//移除监听

[[NSNotificationCenterdefaultCenter]removeObserver:selfname:@"UIDeviceProximityStateDidChangeNotification"object:nil];

}

//处理监听触发事件

-(void)sensorStateChange:(NSNotificationCenter*)notification;

{

//如果此时手机靠近面部放在耳朵旁,那么声音将通过听筒输出,并将屏幕变暗(省电啊)

if([[UIDevicecurrentDevice]proximityState] ==YES)

{

NSLog(@"Device is close to user");

[[AVAudioSessionsharedInstance]setCategory:AVAudioSessionCategoryPlayAndRecorderror:nil];

}

else

{

NSLog(@"Device is not close to user");

[[AVAudioSessionsharedInstance]setCategory:AVAudioSessionCategoryPlaybackerror:nil];

}

}

}

- (void)levelTimer:(NSTimer *)time {

self.timeLabel.text = [NSString stringWithFormat:@"%f",self.recordering.currentTime];

[self.recordering updateMeters];//刷新音量数据

//获取音量的平均值[recorder averagePowerForChannel:0];

//音量的最大值[recorder peakPowerForChannel:0];

doublelowPassResults = pow(10, (0.05* [self.recordering peakPowerForChannel:0]));

NSLog(@"%lf",lowPassResults);

//最大500

//图片小-》大

if(00.06) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_01.png"]];

}elseif(0.060.13) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_02.png"]];

}elseif(0.130.20) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_03.png"]];

}elseif(0.200.27) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_04.png"]];

}elseif(0.270.34) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_05.png"]];

}elseif(0.340.41) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_06.png"]];

}elseif(0.410.48) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_07.png"]];

}elseif(0.480.55) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_08.png"]];

}elseif(0.550.62) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_09.png"]];

}elseif(0.620.69) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_10.png"]];

}elseif(0.690.76) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_11.png"]];

}elseif(0.760.83) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_12.png"]];

}elseif(0.830.9) {

[self.imageView setImage:[UIImage imageNamed:@"record_animate_13.png"]];

}else{

[self.imageView setImage:[UIImage imageNamed:@"record_animate_14.png"]];

}

}


demo地址下载demo

你可能感兴趣的:(录音 播放 AVAudioSession AVAudioPlayer)