美文网首页
AVFoundation - 音频播放与录制

AVFoundation - 音频播放与录制

作者: DoflaKaiGo | 来源:发表于2019-12-16 14:20 被阅读0次
    一 音频会话

    音频会话:音频会话在应用程序中扮演中间人的角色,可以通过音频会话来控制音频的操作
    所有的应用程序都有音频会话,无论是否使用

    • 音频会话分类(Category):
      AVFoundaation定义了七种分类来描述应用程序所使用的音频行为
      (O:可选,Y:支持, N: 不支持)
    分类 作用 是否允许混音 音频输入 音频输出
    Ambient 游戏,效率工具 Y N Y
    Solo Ambient(默认) 游戏,效率工具 N N Y
    PlayBack 音视频播放器 O N Y
    Record 录音机,视频捕捉 O Y N
    PlayAndRecord VoIP,语言聊天 O Y Y
    Audio Progressing 离线会话和处理 N N N
    Muti-Route 使用外部硬件 N Y Y
    • 设置音频会话分类
    //1. 取得音频会话单例
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *error;
        //2. 设置音频会话分类
        if (![session setCategory:AVAudioSessionCategoryPlayback error:&error]) {
            NSLog(@"设置音频会话分类失败%@",[error localizedDescription]);
        }
        //3. 激活会话
        if([session setActive:YES error:&error]){
            NSLog(@"音频会话激活失败%@",[error localizedDescription]);
        }
    
    • 使用AVAudioPlayer 播放音频:AVAudioPlayer 只能播放本地文件
      NSURL *filePath = [[NSBundle mainBundle]URLForResource:@"aaa" withExtension:@"mp3"];
        AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:filePath error:nil];
        if (audioPlayer) {
          [audioPlayer prepareToPlay];//调用 play 方法的时候会自动调用一次
        }
        [audioPlayer play];//开始播放
        [audioPlayer pause];//暂停
        [audioPlayer stop];//停止
    
        audioPlayer.pan = 0.0; // -1.0 ~ 1.0 立体声播放
        audioPlayer.volume = 0.5; //音量 0.0 ~ 1.0
        audioPlayer.numberOfLoops = -1; //循环播放次数,-1 无限轮播
    

    pausestop都会停止播放,再次调用play都会继续播放,区别在于stop会撤销prepareToPlay方法所做的设置,而pause不会

    • 中断处理
      当正在播放音频的时候,有电话拨入会导致中断,中断发生的时候需要对相应状态做一些处理
    - (void)audioInterruptionNotiSet {
        NSNotificationCenter  *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
    }
    
    - (void)handleInterruption:(NSNotification *)noti {
        NSDictionary *info = noti.userInfo;
        AVAudioSessionInterruptionType type = [info[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
        if (type  == AVAudioSessionInterruptionTypeBegan) {
            //中断开始时的处理 正在播放的音频停止 需要对 UI 设置停止状态
        }
        if (type  == AVAudioSessionInterruptionTypeEnded) {
            // 中断结束的时候处理, 因为中断结束后 原先停止的音频不会自动恢复 需要在结束的时候设置
        }
    }
    
    • 路线改变的处理

    iOS 设置上音频输出设备一般包括麦克风和耳机,麦克风正在播放音频的时候插入耳机.音频会改为耳机输出,当拔出耳机的时候,需要暂停音频播放

    - (void)audioRouteChangeNotiSet {
        NSNotificationCenter  *notiCenter = [NSNotificationCenter defaultCenter];
        [notiCenter addObserver:self selector:@selector(handleInterruption:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
    }
    - (void)handRountChange:(NSNotification *)noti {
        NSDictionary *info = noti.userInfo;
        AVAudioSessionRouteChangeReason reasion = [info[AVAudioSessionRouteChangeReasonKey] unsignedIntegerValue];
        if (reasion  == AVAudioSessionRouteChangeReasonOldDeviceUnavailable) {
            // 当输出路径改变的时候,旧有的路径设备不可用 的时候做处理
            AVAudioSessionRouteDescription *routeDescription = info[AVAudioSessionRouteChangePreviousRouteKey];
            AVAudioSessionPortDescription *portDescription = routeDescription.outputs[0];
            NSString *portType = portDescription.portType;
            if ([portType isEqualToString:AVAudioSessionPortHeadphones]) {
                // 当耳机不可用的时候,说明是拔出耳机 此时需要做的处理
            }
        }
    }
    

    • 音频录制
      音频录制需要设置音频会话分类为Record或者PlayAndRecord,需要对音频格式进行正确设置匹配输出文件的后缀名.
    NSURL *filePath ; //输出文件路径,需指定后缀名
        NSDictionary *recordSetting = @{
                                        AVFormatIDKey : @(kAudioFormatMPEG4AAC),
                                        AVSampleRateKey : @(22050.0f),
                                        AVEncoderBitRateKey : @(16),
                                        AVNumberOfChannelsKey : @(1),
                                        AVVideoQualityKey : @(AVAudioQualityMedium)
                                        };
        NSError *error;
        AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc]initWithURL:filePath settings:recordSetting error:&error];
        [audioRecorder prepareToRecord];
        
        [audioRecorder record];//开始录制
        [audioRecorder stop];// 停止录制
        [audioRecorder pause];//暂停
    
    //获取音频音量信息
        audioRecorder.meteringEnabled = YES;
        [audioRecorder updateMeters];
        float avgpower = [audioRecorder averagePowerForChannel:0];
        float peakpower = [audioRecorder peakPowerForChannel:0];
    

    相关文章

      网友评论

          本文标题:AVFoundation - 音频播放与录制

          本文链接:https://www.haomeiwen.com/subject/icnrnctx.html