AVPlayer消耗了大量的CPU。让app随机卡住

时间:2016-09-20 18:38:59

标签: ios xcode ios9 avplayer

我正在开发一个音乐播放器应用并使用AVPlayer,我必须从文档目录播放音频并直接流式传输。但是我的AVPlayer消耗了大量的CPU,使应用程序停留在随机位置。

App Flow

  1. 发起AVPlayer
  2. 检查播放器是否在内存中 不,如果是,则用新音频替换CurrentItemWithPlayerItem 资产。
  3. 并且流传递了资产的URL
  4. 我能得到任何帮助。

    任何请让我知道音乐应用的CPU消耗是正常的。

    由于

        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString* documentsDirectory = [pathArray objectAtIndex:0];
    
    
    NSString* filePath = [documentsDirectory returnDocumentDirectoryPath:@"filename.mp3"];
    NSURL *soundURL;
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        soundURL = [NSURL fileURLWithPath:filePath isDirectory:NO];
    }
    
    if (_player != nil){
        [_player pause];
        [_player removeObserver:self forKeyPath:@"status"];
    }
    
    
    AVAsset *asset = [AVURLAsset URLAssetWithURL:soundURL options:nil];
    AVPlayerItem *anItem = [AVPlayerItem playerItemWithAsset:asset];
    
    _player = [AVPlayer playerWithPlayerItem:anItem];
    [_player addObserver:self forKeyPath:@"status" options:0 context:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[_player currentItem]];
    

    使用以下代码更改音轨时

    [_player replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithAsset:[AVURLAsset URLAssetWithURL:soundURL options:nil]]];
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:[_player currentItem]];
        [_player play];
    

    在线直播

     if(!_player)
        _player = [[AVPlayer alloc] init];
    
    
    resourcePath=@"www.google.com/abc.mp3"//stream URL
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL URLWithString:resourcePath] options:nil];
    NSArray *keys     = [NSArray arrayWithObject:@"playable"];
    
    [asset loadValuesAsynchronouslyForKeys:keys completionHandler:^() {
    
        if(!playerPlaying){
            [_player replaceCurrentItemWithPlayerItem:[AVPlayerItem playerItemWithAsset:asset]];
        }
    }];
    

0 个答案:

没有答案