《AVFoundation秘籍》第2章 播放和录制音频

1. Mac和iOS的音频环境

Mac上提供了灵活自由的音频环境,你可以同时听歌,看电影,录制音频,也不会冲突。但是
iOS系统利用音频会话(audio Session)提供了一个可管理的音频环境。

2.理解音频会话

  • 在APPDelegate中 配置音频会话,如果不配置会导致手机“静音”后不会导致 音频播放不出来。
    // 配置音频会话
    AVAudioSession * audioSession = [AVAudioSession sharedInstance];
    NSError * error ;
    // 设置分类
    if (![audioSession setCategory:AVAudioSessionCategoryPlayback error:&error]) {
        NSLog(@"%@",error.description);
    }
    // 激活会话
    if (![audioSession setActive:YES error:&error]) {
        NSLog(@"%@",error.description);
    }
  • 在Capabilities中设置 ,允许后台播放音频。


    image.png
  • 处理中断事件
    添加 AVAudioSession 的中断通知 AVAudioSessionInterruptionNotification

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioInterruptionNotifiction:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];

中断类型有两种AVAudioSessionInterruptionTypeBegan 中断开始;AVAudioSessionInterruptionTypeEnded中断结束

#pragma mark -- 接收到音频中断 通知
- (void)audioInterruptionNotifiction:(NSNotification *)noti{
    NSDictionary * info = noti.userInfo;
    AVAudioSessionInterruptionType type =  [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        // 中断开始 执行停止播放操作
    }else if (type == AVAudioSessionInterruptionTypeEnded){
         AVAudioSessionInterruptionOptions options = [info[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
        if (options == AVAudioSessionInterruptionOptionShouldResume) {
            // 表明会话已经重新激活 可以再次播放
        }
    }
}
  • 音频线路改变
    添加线路改变通知
    // 音频线路改变通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChangeNotification:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
#pragma mark -- 接收音频线路改变 通知
- (void)audioRouteChangeNotification:(NSNotification *)noti{
    NSDictionary * info = noti.userInfo;
    AVAudioSessionRouteChangeReason reason = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
// 音频线路改变的原因 有很多
    if (reason == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
        // 音频线路改变的原因是 旧设备不可用 (如耳机拔掉)
        // 判断之前的音频的输出设备
        AVAudioSessionRouteDescription * previousRoute = info[AVAudioSessionRouteChangePreviousRouteKey];
        AVAudioSessionPortDescription * previousOutput = previousRoute.outputs.firstObject;
        NSString * portType= previousOutput.portType;
        if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
            // 耳机拔掉 停止播放
        }
    }
}

3.使用AVAudioPlayer 播放音频

    self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:@""] error:nil];
    self.audioPlayer.numberOfLoops = -1;// 无限循环
    self.audioPlayer.enableRate = YES;//必须在调用prepareToPlay之前设置。YES:可以对播放率进行控制
    self.audioPlayer.volume = 0.5;//(0,1)音量
    self.audioPlayer.pan = 0.0;//(-1,1) 立体声
    [self.audioPlayer prepareToPlay];
    
    [self.audioPlayer playAtTime:0.2f];// 从哪里开始播放
    self.audioPlayer.currentTime = 0.0f;// 播放进度回到原点

4.使用AVRecorder 录制音频

   // 设置 录制音配 配置
    NSDictionary * audioSettings = @{
                                     AVFormatIDKey:@(kAudioFormatMPEG4AAC),
                                     AVSampleRateKey :@22050.0f,
                                     AVNumberOfChannelsKey:@1
                                     };
    NSError * error ;
    self.audioRecorder = [[AVAudioRecorder alloc]initWithURL:[NSURL URLWithString:@""] settings:audioSettings error:&error];
    [self.audioRecorder prepareToRecord];
  • 音频格式 -- AVFormatIDKey
    kAudioFormatMPEG4AAC = 'aac ',

  • 采样率 -- AVSampleRateKey
    采样率:输入的模拟音频信号每秒的采样数,
    采样率低 (如8kHz) 会导致粗粒感,文件小;
    采样率高 (如44.1kHz)质量高,文件大;
    标准采样率:8000,16000,22050,44100。

  • 通道数 -- AVNumberOfChannelsKey
    1 :单声道
    2 :立体声

  • 麦克风权限

NSMicrophoneUsageDescription
    xxxx想访问您的麦克风,进行语音通话。

5.音频测量

- (void)levels{
    self.audioRecorder.meteringEnabled = YES;// 支持对音频的e测量
    // 保证读取的级别是最新的
    [self.audioRecorder updateMeters];
    // 想通道0 请求平均值
    float aver = [self.audioRecorder averagePowerForChannel:0];
    // 想通道0 请求峰值
    float peak = [self.audioRecorder peakPowerForChannel:0];
}

你可能感兴趣的:(《AVFoundation秘籍》第2章 播放和录制音频)