iOS-進階整理14 - 多媒體

如果要音樂支持后臺播放

在AppDelegate.m的didFinishLaunch方法里面寫下面

    //支持后臺播放
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //激活
    [session setActive:YES error:nil];
    
   

在info.plist里面修改


一、System Sound Service

它是最底層也是最簡單的聲音播放服務,通過調用AudioServicesPlaySystemSound這個函數就可以播放一些簡單的音頻文件
適用場景:很小的提示或者警告音
局限性

1.聲音長度小于30秒
2.格式 IMA4
3.不能控制播放的進度
4.調用方法后立即播放聲音
5.沒有循環播放和立體聲音播放

   //先從bundle中獲取音頻文件
    NSString *musicPath = [[NSBundle mainBundle]pathForResource:@"news" ofType:@"wav"];
    
    //播放音頻時,需要的路徑為url
    NSURL *musicUrl = [NSURL fileURLWithPath:musicPath];
    //創建soundID 播放系統提示音或者指定的音頻文件,都是根據soundID來找音頻文件,大小范圍為1000~2000
    SystemSoundID mySoundID;
    //創建
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)musicUrl, &mySoundID);
    //播放純音樂
    AudioServicesPlaySystemSound(mySoundID);
    
    //提示音和震動
    AudioServicesPlayAlertSound(mySoundID); 

二、AVAudioPlayer

我們可以把AVAudioPlayer看作一個高級的播放器,它支持廣泛的音頻格式
優勢

1.支持更多格式
2.可播放任意長度
3.支持循環
4.可以同步播放多個
5.控制播放進度以及從音頻的任意一點開始


//AVAudioPlayer
- (IBAction)avAudioPlayer:(UIButton *)sender {
   
    //得到音頻資源
    NSString *musicPath = [[NSBundle mainBundle]pathForResource:@"小豬歌" ofType:@"mp3"];
    //轉換為URL
    NSURL *musicUrl = [NSURL fileURLWithPath:musicPath];
    //創建player對象
    _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:musicUrl error:nil];
    //設置聲音0~1
    _audioPlayer.volume = 0.5;
    //準備播放
    [_audioPlayer prepareToPlay];
   
    //播放進度
//    _audioPlayer.currentTime = 0;    
    //循環播放次數 負數無限循環
//    _audioPlayer.numberOfLoops = -1;
    
    //播放
    [_audioPlayer play];    
    //暫停
    //[_audioPlayer pause];
    //停止
    //[_audioPlayer stop];
}

三、視頻AVPlayer

iOS里視頻播放使用AVPlayer,比AVAudioPlayer更強大,可以直接播放網絡音視頻
AVPlayerItem,資源管理對象,作用:切換視頻播放,

1.狀態 status
AVPlayerItemStatusUnknown,未知
AVPlayerItemStatusReadyToPlay,準備好播放,可以paly
AVPlayerItemStatusFailed,失敗
2.loadedTimeRange
代表緩存的進度,監聽此屬性可以在UI中更新緩存進度

播放完成的通知,可以注冊通知,做出響應
AVPlayerItemDidPlayToEndTimeNotification

**AVPlayerLayer **
單純使用AVPlayer無法顯示視頻,因為這個類并沒有真正的視圖,需要將視頻層添加到AVPlayerLayer中


@property (nonatomic,retain)AVPlayer *player;//播放器
@property (nonatomic,retain)AVPlayerItem *playerItem;//播放對象
@property (nonatomic,retain)AVPlayerLayer *playerLayer;//顯示視頻的層
@property (weak, nonatomic) IBOutlet UISlider *videoSlider;//視頻播放進度
@property (nonatomic,assign)BOOL isReayToPlay;//判斷是否已經開始播放O
@property (weak, nonatomic) IBOutlet UILabel *timeLabel; //顯示事件的label
@property (nonatomic,retain)NSTimer *timer;


- (void)viewDidLoad {
    [super viewDidLoad];
    //還沒有準備好播放視頻
    _isReayToPlay = NO;    
    //啟動視頻準備
    [self netVideoPlay];
     //計時器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
}

//得到視頻
-(void)netVideoPlay
{
    NSString *urlStr =  @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4";
    NSString *urlStr2 = [[NSBundle mainBundle]pathForResource:@"test" ofType:@"mp4"];

    //播放下一個視頻
//    [_player replaceCurrentItemWithPlayerItem: nextPlayerItem];
    
    //得到視頻資源的URL
    NSURL *videoURL = [NSURL fileURLWithPath:urlStr2];
    
    //初始化item
    _playerItem = [[AVPlayerItem alloc]initWithURL:videoURL];
    //初始化播放器
    _player = [AVPlayer playerWithPlayerItem:_playerItem];
    
    //顯示圖像的layer
    _playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    //將視頻層添加到當前解密的layer上
    [self.view.layer addSublayer:_playerLayer];
    _playerLayer.frame = CGRectMake(100, 100, 200, 200);
    //讓視頻層適應當前界面
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    //為item添加觀察者,當視頻已經準備好播放的時候再播放
    [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
}


#pragma mark -- KVO回調方法

//keyPath:變化的屬性的名稱  如果屬性是聲明在.m中就監測不到?
//object:被觀察的對象
//change:存放屬性變化前后的值
//context:添加觀察者時候context的值
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *item = (AVPlayerItem*)object;
    NSLog(@"item -- %@",item);
    //取出變化之后的屬性值
    NSLog(@"new -- %@ ",change[NSKeyValueChangeNewKey]);
    //取出變化之前的
    NSLog(@"old -- %@",change[NSKeyValueChangeOldKey]);
    
    //得到改變后的status
    AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey]intValue];
    //對比,看目前播放單元的狀態
    switch (status) {
        case AVPlayerItemStatusUnknown:
            NSLog(@"未知狀態");
            break;
        case AVPlayerItemStatusFailed:
            NSLog(@"失敗");
            break;
        case AVPlayerItemStatusReadyToPlay:
        {
            NSLog(@"準備好播放");
            [self.player play];
            _isReayToPlay = YES;
        }
            break;
        default:
            break;
    }   
    //視頻的總長度
    float second = _playerItem.duration.value/_playerItem.duration.timescale;
    NSLog(@"視頻長度 %f",second);
    //設置滑竿的最大值
    _videoSlider.maximumValue = second;
    _videoSlider.minimumValue = 0;

    //移除觀察者
    [item removeObserver:self forKeyPath:@"status"];


這里略去了很多東西,我們應該添加一個sliderView,通過NSTimer的方法,來實時顯示視頻的播放進度,同時移動sliderView時可以控制視頻的播放進度。


//進度條的回調方法
-(void)changeProgress:(UISlider*)sender
{
    //每次調整之前,暫停播放
    [_player pause];
    if (_isReayToPlay) {
        //說明已經有時長了,可以進行操作
        //設置播放的區間
        //參數1.CMTime從哪個時刻開始播放
        //參數2.回調,設置完成后要進行的動作
        [self.player seekToTime:CMTimeMakeWithSeconds(sender.value, self.playerItem.currentTime.timescale) completionHandler:^(BOOL finished) {
            if (finished) {
                //調整已經結束,可以播放了
                [_player play];
            }
        }];
    }
}

//進度條根據播放進度變動
-(void)progressAction
{
    //label顯示當前時間
    NSDate *currentTime =[NSDate dateWithTimeIntervalSinceReferenceDate:round(_playerItem.currentTime.value/_playerItem.currentTime.timescale)];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"mm:ss"];
    _timeLabel.text=[formatter stringFromDate:currentTime];
    
    //進度條變動
    _videoSlider.value = _playerItem.currentTime.value/_playerItem.currentTime.timescale;
}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容