控制中心,暂停/播放我的音频流

时间:2015-10-07 10:10:59

标签: audio ios9 avplayer avplayeritem mpnowplayinginfocenter

希望问题转到正确的流程。

我玩HLS,即我使用AVPlayer从服务器播放混合内容(音频和纯视频)。

我将应用程序移动到后台后继续播放音频:我在plist中启用了此功能,此外我还存储Prev Player,禁用可视轨道,并设置为nil AVPlayerLayer。 以下是方法:

- (void)changePlayerState:(BOOL)restored
{
    if (restored && !self.storedPlayer)
        return;
    if (!restored){
        self.storedPlayer  = self.playerView.player;
        [self.playerView setPlayer:nil];
    } else if (self.storedPlayer) {
        [self.playerView setPlayer:self.storedPlayer];
        self.storedPlayer = nil;
    }
    AVPlayerItem *playerItem = self.playerView.playerItem;
    NSArray *tracks = [playerItem tracks];
    for (AVPlayerItemTrack *playerItemTrack in tracks)
    {
        //
        if ([playerItemTrack.assetTrack hasMediaCharacteristic:AVMediaCharacteristicVisual])
            playerItemTrack.enabled = restored; //
    }
}

以下一个:

- (void)setPlayer:(AVPlayer *)player
{
    if (_player != player) {
        [self removePlayerObservers];
        _player = player;
        [self configurePlayerLayer];

        if (_player)
            [self addPlayerObservers];
    }
}
- (void)removePlayerObservers
{
    if ([_player observationInfo] != nil) {
        [_player removeObserver:self
                     forKeyPath:@"rate"
                        context:NPUIPlayerViewPlayerRateObservationContext];
        [_player removeObserver:self
                     forKeyPath:@"isExternalPlaybackActive"
                        context:NPUIPlayerViewAirPlayVideoActiveObservationContext];
    }
    [self removePeriodicTimeObserver];
}
- (void)addPlayerObservers {
    [_player addObserver:self
              forKeyPath:@"rate"
                 options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                 context:NPUIPlayerViewPlayerRateObservationContext];
    [_player addObserver:self
              forKeyPath:@"isExternalPlaybackActive"
                 options:NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew
                 context:NPUIPlayerViewAirPlayVideoActiveObservationContext];
     [self addPeriodicTimeObserver];
}
- (void)removePeriodicTimeObserver
{
    if (_registeredTimeObserver) {
        [_player removeTimeObserver:_registeredTimeObserver];
        _registeredTimeObserver = nil;
    }
}
- (void)addPeriodicTimeObserver
{
    __weak NPUIPlayerView *weakSelf = self;
    _registeredTimeObserver = [_player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(0.5f, 10) queue:dispatch_get_main_queue()

所以在将应用程序移动到后台,按下HOme按钮,然后激活控制中心(从按钮向上滑动,在哪里是计算器,相机,灯光按钮),我可以设置正在播放的项目的标题,但是Apple& #39;播放器控制不起作用:按暂停,播放也不起作用滑块也不起作用。 当我按下按钮时,我确实收到了事件,但同时,尽管如此,我称之为[播放器暂停],或更改速率,它不会更改按钮。但是当通过互联网访问音频时出现问题,或者声音缓冲区为空时,按钮会被更改,它会暂停UI。 下面是设置现在播放媒体中心和添加命令的代码

- (void)adjustNowPlayingScreen
{
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    NSMutableDictionary *mDic =[NSMutableDictionary dictionary];
    NSString *newTitle = self.playerTitle.text ?: self.itemToPlay.shortName ?: self.itemToPlay.name ?: @"";
    if (newTitle.length)
        mDic[MPMediaItemPropertyTitle] = newTitle;
    AVPlayerItem * item = [self.playerView.player currentItem];
    CMTime itemDuration = [self.playerView.player.currentItem duration];
    if (CMTIME_IS_VALID(itemDuration) ) {
        NSTimeInterval duration = CMTimeGetSeconds(itemDuration);

        if (duration)
            mDic[MPMediaItemPropertyPlaybackDuration] = @(duration);
    }
    else
    {
        NSTimeInterval duration = CMTimeGetSeconds([item.asset duration]);
        if (!isnan(duration) && duration > 0)
            mDic[MPMediaItemPropertyPlaybackDuration] = @(duration);
        else {
            duration =  CMTimeGetSeconds([[[[self playerView] playerItem] asset] duration]);
            if (!isnan(duration) && duration > 0)
                mDic[MPMediaItemPropertyPlaybackDuration] = @(duration);
        }
    }
    NSString *urlStr = self.itemToPlay.autoQualityURL ?: self.itemToPlay.lowAutoQualityURL;
    if (urlStr.length)
        mDic[MPMediaItemPropertyAssetURL] = urlStr;
    CMTime curTime = self.playerView.playerItem.currentTime;
    if (CMTIME_IS_VALID(curTime)) {

        NSTimeInterval duration = CMTimeGetSeconds(curTime);
        mDic[MPNowPlayingInfoPropertyElapsedPlaybackTime]= @(duration);
    }
    if (mDic.count) {
#warning @"HACK: Necessary to change number of played items & index"

        mDic[ MPMediaItemPropertyAlbumTrackNumber] = @(1);
        mDic[ MPMediaItemPropertyAlbumTrackCount]  = @(1);

        mDic[ MPNowPlayingInfoPropertyPlaybackRate] = @(self.playerView.isPlaying ? 1.0 : 0.0);
        UIImage *img = [UIImage imageNamed:@"team_4f6ae0b99d4b856118000124"];
        mDic[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc]initWithImage:img];
        infoCenter.nowPlayingInfo = mDic;
    }
}
- (void)addRemoteCommands
{
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    MPRemoteCommand *command = [commandCenter pauseCommand];
    command.enabled = true;
    [command addTarget:self action:@selector(pauseCommand:)];
    command = [commandCenter playCommand];
    command.enabled = true;
    [command addTarget:self action:@selector(playCommand:)];
    command = [commandCenter togglePlayPauseCommand];
    command.enabled = true;
    [command addTarget:self action:@selector(toggleCommand:)];
    command = [commandCenter seekForwardCommand];
    command.enabled = true;
    [command addTarget:self action:@selector(seekForwardCommand:)];
    command = [commandCenter seekBackwardCommand];
    command.enabled = true;
    [command addTarget:self action:@selector(seekBackwardCommand:)];
}
- (void)updateElapsedTime
{
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    MPRemoteCommand *command = [commandCenter togglePlayPauseCommand];
    if (!command.enabled)
        return;
    [self adjustNowPlayingScreen];
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2);
    dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void){
        [self updateElapsedTime];
    });
}
- (void)removeRemoteCommands
{
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    MPRemoteCommand *command = [commandCenter pauseCommand];
    command.enabled = false;
    [command removeTarget:self action:@selector(pauseCommand:)];
    command = [commandCenter playCommand];
    command.enabled = false;
    [command removeTarget:self action:@selector(playCommand:)];
    command = [commandCenter togglePlayPauseCommand];
    command.enabled = false;
    [command removeTarget:self action:@selector(toggleCommand:)];
    command = [commandCenter seekForwardCommand];
    command.enabled = false;
    [command removeTarget:self action:@selector(seekForwardCommand:)];
    command = [commandCenter seekBackwardCommand];
    command.enabled = false;
    [command removeTarget:self action:@selector(seekBackwardCommand:)];
}
- (void)seekBackwardCommand:(MPRemoteCommandEvent *)event
{
    NSLog(@"%@",NSStringFromClass([event class]));
}
- (void)seekForwardCommand:(MPRemoteCommandEvent *)event
{
    NSLog(@"%@",NSStringFromClass([event class]));
}
- (void)pauseCommand:(MPRemoteCommandEvent *)event
{
    [self pause];    //_player pause];
    AVPlayerItem *playerItem = self.playerView.playerItem;
    NSArray *tracks = [playerItem tracks];
    for (AVPlayerItemTrack *playerItemTrack in tracks)
    {
        /
        if ([playerItemTrack.assetTrack hasMediaCharacteristic:AVMediaCharacteristicAudible])
            playerItemTrack.enabled = false; /
    }
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    NSMutableDictionary *mDic =[NSMutableDictionary dictionaryWithDictionary:infoCenter.nowPlayingInfo];
    mDic[ MPNowPlayingInfoPropertyPlaybackRate] = @(0.0);
    infoCenter.nowPlayingInfo = mDic;
}

所以,我的暂停命令被调用,我称之为AVPlayer的暂停方法。但它并没有停止音频流。

Slider不起作用,因此我的seekBackwardCommand / seekForwardCommand不会被调用。

但正如我所说,当流结束时(音频也是如此),控制中心上的播放器将按钮从播放变为暂停,即以某种方式监听音频会话的变化。

我通过设置AVAudioSessionCategoryPlayback和设置模式来调整声音类别:AVAudioSessionModeMoviePlayback

请帮助您如何正确处理控制屏幕上的暂停/播放按钮,如何启用滑块?

我在iOS9,iPhone 6上运行我的代码。

0 个答案:

没有答案