调用系统功能-录音/播放音效/音频/视频

调用系统功能 录音/播放音效/音频
框架< AVFoundation/AVFoundation.h >
1. 录音
  • 设置音频管理
    // 设置音频管理
    AVAudioSession *session = [AVAudioSession sharedInstance];
    // 设置只用于录音
    NSError *error;
    [session setCategory:AVAudioSessionCategoryRecord error:&error];
    if (session == nil) {
        NSLog(@"创建失败:%@",[error description]);
    } else {
        // 激活
        [session setActive:YES error:nil];
    }
  • 开始录音
    //获取沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingString:@"/record.caf"];

    //获取文件路径
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];

    //设置参数
    NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
    //采样率  8000/11025/22050/44100/96000(影响音频的质量)
    [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
    // 音频格式
    [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
    //采样位数  8、16、24、32 默认为16
    [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
    // 音频通道数 1 或 2
    [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
    //录音质量
    [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,nil];

    AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:recordSetting error:nil];
    // 通过音频测量值可以即时获得音频分贝等信息
    recorder.meteringEnabled = YES;
    // 准备录音
    [recorder prepareToRecord];
    // 开始录音
    [recorder record];
  • 结束录音
   // 结束录音
    if ([recorder isRecording]) {
        [recorder stop];
    }
  • 播放录音
    // 播放录音
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:nil];
    // 设置只用于播放
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [player play];
  • 实现AVAudioRecorderDelegate代理
// 执行stop时调用
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    NSLog(@"录音完成");
}
  • 获取录音过程中的分贝(要在录音过程中获取分贝数,要在录音前先把AVAudioRecorder的属性meteringEnabled设置成YES.)
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(getPeakPower) userInfo:nil repeats:YES];

-(void)getPeakPower {
    if (self.audioRecorder.isRecording) {
        [self.audioRecorder updateMeters];
        float peakPower = [self.audioRecorder peakPowerForChannel:0];
        NSLog(@"%f", peakPower);
    }
}
2. 播放音效
    // 创建SystemSoundID,根据音效文件生成
    SystemSoundID soundId = 0;
    // 创建文件地址
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];
    // 桥接CFURLRef
    CFURLRef urlref = (__bridge CFURLRef)(url);

    // 根据音效文件创建AudioServicesCreateSystemSoundID
    AudioServicesCreateSystemSoundID(urlref, &soundId);

    // 播放音效
    AudioServicesPlayAlertSound(soundId); // 会震动
    AudioServicesPlaySystemSound(soundId); // 不会震动
    AudioServicesPlayAlertSoundWithCompletion(soundId, nil);// 将要替代上面AudioServicesPlaySystemSound方法

    // 释放音效资源
    AudioServicesDisposeSystemSoundID(soundId);
  • 封装
@property (nonatomic,assign) SystemSoundID soundId;
/** 存放音效文件字典 */
@property (nonatomic,strong) NSMutableDictionary *soundIDs;

- (NSMutableDictionary *)soundIDs {
    if (!_soundIDs) {
        _soundIDs = [NSMutableDictionary dictionary];
    }
    return _soundIDs;
}

- (SystemSoundID)soundId {
    if (_soundId == 0) {
        // 创建文件地址
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];
        // 桥接CFURLRef
        CFURLRef urlref = (__bridge CFURLRef)(url);

        // 根据音效文件创建AudioServicesCreateSystemSoundID
        AudioServicesCreateSystemSoundID(urlref, &_soundId);
    }
    return _soundId;
}

- (void)play {
    // 定义SystemSoundID
    SystemSoundID soundId = 0;

    // 从字典中取出对应的音效文件
    soundId = [self.soundIDs[@""] unsignedIntValue];
    // 判断如果取出为空,则创建新的soundId
    if (soundId == 0) {
        // 创建文件地址
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];
        // 桥接CFURLRef
        CFURLRef urlref = (__bridge CFURLRef)(url);
        // 根据音效文件创建AudioServicesCreateSystemSoundID
        AudioServicesCreateSystemSoundID(urlref, &soundId);

        // 将soundId存入字典中,下次就可以不用再次创建
        [self.soundIDs setObject:@(soundId) forKey:@""];
    }
    // 播放音效
    AudioServicesPlayAlertSound(soundId); // 会震动
}
3. 播放音乐
  • 创建播放器
- (AVAudioPlayer *)player {
    if (_player == nil) {
        // 获取本音乐文件
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];
        // 根据音乐地址创建播放器
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        // 准备播放
        [self.player prepareToPlay];
    }
    return _player;
}
  • 对象方法
- (BOOL)prepareToPlay; // 准备播放
- (BOOL)play; // 播放
- (BOOL)playAtTime:(NSTimeInterval)time;// 在指定时间播放音频
- (void)pause; // 暂停播放
- (void)stop; // 停止播放
  • 属性
@property NSTimeInterval currentTime; // 当前播放的时间
@property(readonly) NSTimeInterval duration; // 播放器的总时间
  • 代理
// 播放完成调用
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag;
// 播放解析错误调用
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error;
4. 播放视频
  • 初始化播放器
方法一:
- (AVPlayer *)player {
    if (_player == nil) {
        // 获取视频资源
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];
        // 根据资源创建视频播放资源
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url];
        // 创建播放器
        _player = [AVPlayer playerWithPlayerItem:item];
    }
    return _player;
}
方法二:(ios 9过期)
- (MPMoviePlayerController *)playerController {
    if (_playerController == nil) {
        // 获取视频资源
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"" withExtension:nil];
        _playerController = [[MPMoviePlayerController alloc] initWithContentURL:url];
        // 添加视图
        _playerController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.width * 9 / 16);
        [self.view addSubview:_playerController.view];
    }
    return _playerController;
}
  • 对象方法
- (void)play; // 播放
- (void)pause; // 暂停
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值