利用AVFoundation框架实现录音、音效、音视频的播放

文 || 張贺

利用AVFoundation框架可以做什么?

  • 录音
  • 音效
  • 播放远程 / 本地音乐
  • 播放远程 / 本地视频

录音

录音使用AVAudioRecorder这个类来进行录音
#import "ViewController.h"
#import

@interface ViewController ()
@property (nonatomic,strong) AVAudioRecorder *recorder;
@end

@implementation ViewController
 //懒加载
 -(AVAudioRecorder *)recorder{
      if (_recorder == nil) {
          //1.创建沙盒路径
          NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
          //2.拼接音频文件
          NSString *filePath = [path stringByAppendingPathComponent:@"123.caf"];
          //3.转换成url  file://
          NSURL *url = [NSURL fileURLWithPath:filePath];
          //4.设置录音的参数
          NSDictionary *settings = @{
                                     /**录音的质量,一般给LOW就可以了
                                      typedef NS_ENUM(NSInteger, AVAudioQuality) {
                                      AVAudioQualityMin    = 0,
                                      AVAudioQualityLow    = 0x20,
                                      AVAudioQualityMedium = 0x40,
                                      AVAudioQualityHigh   = 0x60,
                                      AVAudioQualityMax    = 0x7F
                                      };*/
                                     AVEncoderAudioQualityKey : [NSNumber numberWithInteger:AVAudioQualityLow],
                                     AVEncoderBitRateKey : [NSNumber numberWithInteger:16],
                                     AVSampleRateKey : [NSNumber numberWithFloat:8000],
                                     AVNumberOfChannelsKey : [NSNumber numberWithInteger:2]
                                     };
          NSLog(@"%@",url);
          //第一个参数就是你要把录音保存到哪的url
          //第二个参数是一些录音的参数
          //第三个参数是错误信息
          self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:settings error:nil];
      }
      return _recorder;
  }
  //开始录音
  - (IBAction)start:(id)sender {
      [self.recorder record];
  }
  //停止录音
  - (IBAction)stop:(id)sender {
      [self.recorder stop];
  }
@end

音效

  • 又称“短音频”,通常在程序中的播放时长为1~2秒
  • 在应用程序中起到点缀效果,提升整体用户体验
#import "ViewController.h"
#import 

@interface ViewController ()
@property (nonatomic,assign)SystemSoundID soundID;
@end

@implementation ViewController

-(SystemSoundID)soundID{
    if (_soundID == 0) {
        //生成soundID
        CFURLRef url = (__bridge CFURLRef)[[NSBundle mainBundle]URLForResource:@"buyao.wav" withExtension:nil];
        AudioServicesCreateSystemSoundID(url, &_soundID);
    }
    return _soundID;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //播放音效
    AudioServicesPlaySystemSound(self.soundID);//不带震动效果
    //AudioServicesPlayAlertSound(<#SystemSoundID inSystemSoundID#>)//带震动效果
}

@end

播放音乐

播放本地音乐

比如游戏中的“背景音乐”,一般播放时间较长
使用AVAudioPlayer只能播放本地音乐

#import "ViewController.h"
#import 

@interface ViewController ()
@property (nonatomic,strong)AVAudioPlayer *player;
@end

@implementation ViewController

-(AVAudioPlayer *)player{
    if (_player == nil) {
        //1.音乐资源
        NSURL *url = [[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:nil];
        //2.创建AVAudioPlayer对象
        _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        //3.准备播放(缓冲,提高播放的流畅性)
        [_player prepareToPlay];
    }
    return _player;
}
//播放(异步播放)
- (IBAction)play {
    [self.player play];
}
//暂停音乐,暂停后再开始从暂停的地方开始
- (IBAction)pause {
    [self.player pause];
}
//停止音乐,停止后再开始从头开始
- (IBAction)stop {
    [self.player stop];
    //这里要置空
    self.player = nil;
}  
@end

播放远程音乐

使用AVPlayer既可以播放本地音乐也可以播放远程(网络上的)音乐
#import "ViewController.h"
#import

@interface ViewController ()
@property (nonatomic,strong)AVPlayer *player;
@end

@implementation ViewController

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //播放音乐
    [self.player play];
}

#pragma mark - 懒加载
-(AVPlayer *)player{
    if (_player == nil) {
            
    //想要播放远程音乐,只要把url换成网络音乐就可以了
    //NSURL *url = [NSURL URLWithString:@"http://cc.stream.qqmusic.qq.com/C100003j8IiV1X8Oaw.m4a?fromtag=52"];

    //1.本地的音乐资源
    NSURL *url = [[NSBundle mainBundle]URLForResource:@"235319.mp3" withExtension:nil];

    //2.这种方法设置的url不可以动态的切换
    _player = [AVPlayer playerWithURL:url];

    //2.0创建一个playerItem,可以通过改变playerItem来进行切歌
    //AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    //2.1这种方法可以动态的换掉url
    //_player = [AVPlayer playerWithPlayerItem:playerItem];
    
    //AVPlayerItem *nextItem = [AVPlayerItem playerItemWithURL:nil];
    //通过replaceCurrentItemWithPlayerItem:方法来换掉url,进行切歌
    //[self.player replaceCurrentItemWithPlayerItem:nextItem];
    
    }
    return _player;
}
@end

播放本地 / 远程视频

使用AVPlayer也可以播放本地 / 远程视频
这种方式只能播放视频,上面是不能点击的,逻辑需要代码去实现
#import "ViewController.h"
#import
@interface ViewController ()

@property(nonatomic,strong)AVPlayer *player;

@end

@implementation ViewController
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    //播放视频
    [self.player play];
}
-(AVPlayer *)player{
    if (_player == nil) {
    
        //播放远程视频
        NSURL *url = [NSURL URLWithString:@"http://v1.mukewang.com/a45016f4-08d6-4277-abe6-bcfd5244c201/L.mp4"];
        //加载本地视频源
        //NSURL *url = [[NSBundle mainBundle]URLForResource:@"xiaohuangren.mp4" withExtension:nil];
    
        //创建播放器
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
        _player = [AVPlayer playerWithPlayerItem:playerItem];
    
        //显示视频的层AVPlayerLayer
        AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
        //视频的宽高比例一般为16 : 9
        playerLayer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width * 9 / 16);
        //把playerLayer添加到控制器的层上
        [self.view.layer addSublayer:playerLayer];
    }
    return _player;
}

@end

使用AVPlayerViewController播放视频

AVPlayerViewController属于AVKit框架,应包含#import
iOS9.0以后AVPlayerViewController取代了
MPMoviePlayerController和MPMoviePlayerViewController

#import "ViewController.h"
#import 
#import 

@interface ViewController ()
@property (nonatomic,strong)AVPlayerViewController *playerVC;
@end

@implementation ViewController

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //以modal的样式弹出来,只能全屏显示
    [self presentViewController:self.playerVC animated:YES completion:nil];
    }

-(AVPlayerViewController *)playerVC{
    if (_playerVC == nil) {
        //视频源
        NSURL *url = [NSURL URLWithString:@"http://v1.mukewang.com/a45016f4-08d6-4277-abe6-bcfd5244c201/L.mp4"];
        //
        AVPlayerItem *platerItem = [AVPlayerItem playerItemWithURL:url];
        //
        AVPlayer *player = [[AVPlayer alloc]initWithPlayerItem:platerItem];
        //创建一个视频播放的控制器
        //这个类实在AVKit框架下的
        _playerVC = [[AVPlayerViewController alloc]init];
        //设置player
        _playerVC.player = player;
    }
    return _playerVC;
}
@end
AVPlayerViewController播放的视频张这样

你可能感兴趣的:(利用AVFoundation框架实现录音、音效、音视频的播放)