IOS音频相关

AVAudioPlayer AVAudioRecorder MPMoviePlayerController Sensor

AVAudioSession


默认设置播放状态 使用以下类必须先设置

AVAudioPlayer AVAudioRecorder MPMoviePlayerController

AVAudioSession *audioSession=[AVAudioSession sharedInstance];
//设置为播放和录音状态,以便可以在录制完之后播放录音
//听筒模式
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
//扬声器模式
[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setActive:YES error:nil];

AVAudioPlayer


-(AVAudioPlayer *)audioPlayer {
   //创建播放器
	if (!_audioPlayer) {
        NSURL *url = [NSURL fileURLWithPath:self.recordPath];
        NSError *error=nil;
        _audioPlayer=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
        [_audioPlayer setVolume:1.0];
        [_audioPlayer setDelegate:self];
        [_audioPlayer prepareToPlay];
        [self.audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        if (error) {
            PKLog(@"创建播放器过程中发生错误,错误信息:%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioPlayer;
}

AVAudioRecorder


-(NSURL *)getSavePath {
    //初始化输出路径
    NSString *voiceName = [NSString stringWithFormat:@"iOS_Voice_%@.aac", [NSDate date]];
    NSString *pathOfCachs = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    self.recordPath = [pathOfCachs stringByAppendingPathComponent:voiceName];
    PKLog(@"%@", self.recordPath);
    NSURL *url = [NSURL fileURLWithPath:self.recordPath];
   return url;
}

-(NSDictionary *)getAudioSetting {
    //取得录音文件设置
    NSMutableDictionary *dicM=[NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    //设置录音采样率,8000是电话采样率,对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [dicM setObject:@(AVAudioQualityHigh) forKey:AVEncoderAudioQualityKey];
    //....其他设置等
    return dicM;
}
-(AVAudioRecorder *)audioRecorder {
     //获得录音机对象
	if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url=[self getSavePath];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        [self.audioSession setCategory:AVAudioSessionCategoryRecord error:nil];
        if (error) {
            PKLog(@"创建录音机对象时发生错误,错误信息:%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

MPMoviePlayerController


	// 语音Url
	NSString *voiceUrl = [[parameter objectForKey:@"args"] lastObject];
	// 强制使用外放!
	[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
	// 播放音频
	self.player.contentURL = [NSURL URLWithString:voiceUrl];
	[self.player play];
        
- (MPMoviePlayerController *)player{
    if (_player == nil) {
        _player = [[MPMoviePlayerController alloc] init];
    }
    return _player;
}

距离传感器


#pragma mark 添加监听距离传感器
- (void)setSensorCall{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:) name:@"UIDeviceProximityStateDidChangeNotification" object:nil];
}    
#pragma mark 开启距离感应器
- (void)openSensor{
    [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
}
#pragma mark 停止距离感应器
- (void)closeSensor{
    [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
}
#pragma mark 距离传感器改变
-(void)sensorStateChange:(NSNotificationCenter *)notification{
    //如果此时手机靠近面部放在耳朵旁,那么声音将通过听筒输出,并将屏幕变暗(省电啊)
    if ([[UIDevice currentDevice] proximityState] == YES)
    {
        PKLog(@"Device is close to user");
        [self.audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    }
    else
    {
        PKLog(@"Device is not close to user");
        [self.audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    }
}