【问题标题】:iOS : how to know if a live audio stream is "On air"?iOS:如何知道实时音频流是否“播出”?
【发布时间】:2012-06-11 14:22:33
【问题描述】:

我正在开发一个必须流式传输实时音频(来自 m3u 远程文件)的应用程序,并且我正在寻找一种方法来检查实时流是“播出”还是“播出”。音频播放器使用AVPlayer

我做了功课,但没有找到关于该主题的任何内容...

非常感谢...

【问题讨论】:

    标签: ios avplayer live-streaming


    【解决方案1】:

    当你使用 AVPlayer 和 AVPlayerItem 时,像下面这样添加观察者:

    -(void) addMediaObservers {
        [_playerItem addObserver:self forKeyPath:@"player_buffer_empty" options:0 context:@"player_buffer_empty"];
        [_playerItem addObserver:self forKeyPath:@"item_status" options:0 context:@"item_status"];
    
        [_player addObserver:self forKeyPath:@"player_status" options:0 context:@"player_status"];
    }
    

    请不要忘记在停止流式传输时或在 dealloc 方法中删除这些观察者。

    - (void)stop
    {
        [_playerItem removeObserver:self forKeyPath:@"player_buffer_empty"];
        [_playerItem removeObserver:self forKeyPath:@"item_status"];
        [_player removeObserver:self forKeyPath:@"player_status"];
    }
    

    您将通过以下方法管理音频流:

    - (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
    {
        if (context && ([context isEqualToString:@"item_status"] || [context isEqualToString:@"player_status"] || [context isEqualToString:@"player_buffer_empty"]))
        {
            [self checkStatus];
        }
    }
    
    - (void)checkStatus
    {
        AVPlayerItemStatus ps = _playerItem && _playerItem.status ? _playerItem.status : AVPlayerItemStatusUnknown;
        AVPlayerStatus s = _player && _player.status ? _player.status : AVPlayerStatusUnknown;
    
        BOOL isReady = ps == AVPlayerItemStatusReadyToPlay && s == AVPlayerStatusReadyToPlay;
    
        if (_isPlaying) {
            if (!_isLoading && _player && _playerItem && _playerItem.playbackBufferEmpty) {
                _isLoading = YES;
                [self performSelector:@selector(unpause) withObject:nil afterDelay:20];
            }
            if (!isReady)
                [self stop];
        } else {
            if (isReady)
                [self play];
        }
    }
    

    方法范围内未声明的方法中使用的所有变量都是全局变量。 我希望这会有所帮助!

    【讨论】:

    • 您应该避免将 keyPath 与字符串进行比较,而是使用上下文。您再次使用上下文的方式非常奇怪。为什么要交出必须使用字符串操作进行比较的字符串指针?
    • @Till 我同意你的解释。在这种情况下,完全没有必要使用 keyPath。很抱歉失败了。我将编辑我的答案。
    • 非常感谢,今晚回家试试这个。
    • @adhumi 如果有用,请不要忘记对我的回答进行限定!
    猜你喜欢
    • 2014-05-05
    • 2010-11-21
    • 2018-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多