2012-06-19 57 views
5

我想用AVPlayer播放我的iPhone音乐库中的歌曲。一切似乎都准备好了,但玩家根本不会发出任何声音。我一直在努力这一段时间,任何帮助将不胜感激!AVPlayer没有从音乐库中播放

注意:我意识到我可以使用AVAudioPlayer,但我想从我的音乐库中直接读取文件,并且据我了解,AVAudioPlayer不支持该功能(我必须先导出歌曲,更多时间)。我无法使用MPMusicPlayerController,因为最终目标是将歌曲转换为NSData并在其他设备上播放。

首先,我想知道为什么这个代码是不是在玩:

NSArray *itemsFromQuery = [[MPMediaQuery songsQuery] items]; 
MPMediaItem *song = [itemsFromQuery objectAtIndex:29]; 
NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL]; 
AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:songURL options:nil]; 

NSArray *keyArray = [[NSArray alloc] initWithObjects:@"tracks", nil]; 

[urlAsset loadValuesAsynchronouslyForKeys:keyArray completionHandler:^{ 

    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:urlAsset]; 

    AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem]; 

    while (true) { 
     if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) { 
      break; 
     } 
    } 

    if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) { 
     NSLog(@"Ready to play"); 
     [player play]; 
    } 
    else 
     NSLog(@"Not ready to play"); 
}]; 

输出为“准备好了玩”和“速度”的AVPlayer的属性是1.0我打电话后,玩法。 MPMediaItem存在,我可以使用valueForProperty方法获得正确的标题,艺术家等等。为什么没有声音来自播放器?

+1

你是否尝试在块外面声明AVPlayer和AVPlayerItem,就像'NSArray * keyArray'之后一样? – meggar

+0

我做到了。在外部声明并初始化它们并没有什么区别。在外部声明它们并在处理程序中初始化它们显然是被禁止的。谢谢你的想法! – JohnG

回答

12

找到一些工作:

  1. 我所做的AVPlayer属性(感谢小费meggar!)
  2. 我确定AVPlayer是使用initWithAsset方法之前为零。

    NSArray *itemsFromQuery = [[MPMediaQuery songsQuery] items]; 
    MPMediaItem *song = [itemsFromQuery objectAtIndex:0]; 
    NSURL *songURL = [song valueForProperty:MPMediaItemPropertyAssetURL]; 
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:songURL options:nil]; 
    
    NSArray *keyArray = [[NSArray alloc] initWithObjects:@"tracks", nil]; 
    
    [urlAsset loadValuesAsynchronouslyForKeys:keyArray completionHandler:^{ 
    
        AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:urlAsset]; 
    
        player = nil; 
        player = [[AVPlayer alloc] initWithPlayerItem:playerItem]; 
    
        while (true) { 
         if (player.status == AVPlayerStatusReadyToPlay && playerItem.status == AVPlayerItemStatusReadyToPlay) 
          break; 
        } 
    
        [player play]; 
    
    }]; 
    

希望这有助于有人出来!

+1

非常感谢。真。谢谢。很多。 – duci9y

1

另一个原因是配置AVAudioSession。为我工作。

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
    [[AVAudioSession sharedInstance] setActive: YES error: nil];