AVFoundation - 音频播放与录制

2019-12-16  本文已影响0人  DoflaKaiGo
一 音频会话

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

分类 作用 是否允许混音 音频输入 音频输出
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]);
    }
  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]) {
            // 当耳机不可用的时候,说明是拔出耳机 此时需要做的处理
        }
    }
}

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];
上一篇下一篇

猜你喜欢

热点阅读