利用AVFoundation框架實(shí)現(xiàn)錄音、音效、音視頻的播放

文 || 張賀

利用AVFoundation框架可以做什么?

  • 錄音
  • 音效
  • 播放遠(yuǎn)程 / 本地音樂
  • 播放遠(yuǎn)程 / 本地視頻

錄音

錄音使用AVAudioRecorder這個類來進(jìn)行錄音
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

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

@implementation ViewController
 //懶加載
 -(AVAudioRecorder *)recorder{
      if (_recorder == nil) {
          //1.創(chuàng)建沙盒路徑
          NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
          //2.拼接音頻文件
          NSString *filePath = [path stringByAppendingPathComponent:@"123.caf"];
          //3.轉(zhuǎn)換成url  file://
          NSURL *url = [NSURL fileURLWithPath:filePath];
          //4.設(shè)置錄音的參數(shù)
          NSDictionary *settings = @{
                                     /**錄音的質(zhì)量,一般給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);
          //第一個參數(shù)就是你要把錄音保存到哪的url
          //第二個參數(shù)是一些錄音的參數(shù)
          //第三個參數(shù)是錯誤信息
          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秒
  • 在應(yīng)用程序中起到點(diǎn)綴效果,提升整體用戶體驗(yàn)
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@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<UITouch *> *)touches withEvent:(UIEvent *)event{
    //播放音效
    AudioServicesPlaySystemSound(self.soundID);//不帶震動效果
    //AudioServicesPlayAlertSound(<#SystemSoundID inSystemSoundID#>)//帶震動效果
}

@end

播放音樂

播放本地音樂

比如游戲中的“背景音樂”,一般播放時間較長
使用AVAudioPlayer只能播放本地音樂

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@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.創(chuàng)建AVAudioPlayer對象
        _player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        //3.準(zhǔn)備播放(緩沖,提高播放的流暢性)
        [_player prepareToPlay];
    }
    return _player;
}
//播放(異步播放)
- (IBAction)play {
    [self.player play];
}
//暫停音樂,暫停后再開始從暫停的地方開始
- (IBAction)pause {
    [self.player pause];
}
//停止音樂,停止后再開始從頭開始
- (IBAction)stop {
    [self.player stop];
    //這里要置空
    self.player = nil;
}  
@end

播放遠(yuǎn)程音樂

使用AVPlayer既可以播放本地音樂也可以播放遠(yuǎn)程(網(wǎng)絡(luò)上的)音樂
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

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

@implementation ViewController

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

#pragma mark - 懶加載
-(AVPlayer *)player{
    if (_player == nil) {
            
    //想要播放遠(yuǎn)程音樂,只要把url換成網(wǎng)絡(luò)音樂就可以了
    //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.這種方法設(shè)置的url不可以動態(tài)的切換
    _player = [AVPlayer playerWithURL:url];

    //2.0創(chuàng)建一個playerItem,可以通過改變playerItem來進(jìn)行切歌
    //AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    //2.1這種方法可以動態(tài)的換掉url
    //_player = [AVPlayer playerWithPlayerItem:playerItem];
    
    //AVPlayerItem *nextItem = [AVPlayerItem playerItemWithURL:nil];
    //通過replaceCurrentItemWithPlayerItem:方法來換掉url,進(jìn)行切歌
    //[self.player replaceCurrentItemWithPlayerItem:nextItem];
    
    }
    return _player;
}
@end

播放本地 / 遠(yuǎn)程視頻

使用AVPlayer也可以播放本地 / 遠(yuǎn)程視頻
這種方式只能播放視頻,上面是不能點(diǎn)擊的,邏輯需要代碼去實(shí)現(xiàn)
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ViewController ()

@property(nonatomic,strong)AVPlayer *player;

@end

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

    //播放視頻
    [self.player play];
}
-(AVPlayer *)player{
    if (_player == nil) {
    
        //播放遠(yuǎn)程視頻
        NSURL *url = [NSURL URLWithString:@"http://v1.mukewang.com/a45016f4-08d6-4277-abe6-bcfd5244c201/L.mp4"];
        //加載本地視頻源
        //NSURL *url = [[NSBundle mainBundle]URLForResource:@"xiaohuangren.mp4" withExtension:nil];
    
        //創(chuàng)建播放器
        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框架,應(yīng)包含#import <AVKit/AVKit.h>
iOS9.0以后AVPlayerViewController取代了
MPMoviePlayerController和MPMoviePlayerViewController

#import "ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>

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

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)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];
        //創(chuàng)建一個視頻播放的控制器
        //這個類實(shí)在AVKit框架下的
        _playerVC = [[AVPlayerViewController alloc]init];
        //設(shè)置player
        _playerVC.player = player;
    }
    return _playerVC;
}
@end
AVPlayerViewController播放的視頻張這樣
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容