将MPMediaItems与AVAudioPlayer一起使用

jar*_*ryd 28 iphone objective-c

是否可以使用MPMediaPickerController选择媒体项目,然后将它们加载到AVAudioPlayer对象中?

Art*_*pie 48

如果MPMusicPlayerController不能满足您的需求,您可以将音频复制到本地捆绑包,以便您可以使用AVAudioPlayer.

编辑

你基本上从用户的iPod库中播放音频三个选项:MPMediaPlayer,AVPlayerAVAudioPlayer.

以下是MPMediaPlayer和的示例AVPlayer:

- (void) mediaPicker: (MPMediaPickerController *) mediaPicker
   didPickMediaItems: (MPMediaItemCollection *) collection {


    MPMediaItem *item = [[collection items] objectAtIndex:0];
    NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];

    [self dismissModalViewControllerAnimated: YES];

    // Play the item using MPMusicPlayer

    MPMusicPlayerController* appMusicPlayer = [MPMusicPlayerController applicationMusicPlayer];

    [appMusicPlayer setQueueWithItemCollection:collection];
    [appMusicPlayer play];


    // Play the item using AVPlayer

    AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithURL:url];
    AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:playerItem];
    [player play];  

}
Run Code Online (Sandbox Code Playgroud)

如果AVAudioPlayer由于某种原因需要使用,或者需要访问音频文件的实际音频数据,则必须先将音频文件复制到应用程序的目录中,然后在那里使用它.该AVAsset+ AVPlayer东西是最接近的比喻ALAsset,如果你已经习惯了用照片和视频的工作.

  • 使用此:MPMediaItem*item = [[collection items] objectAtIndex:0]; NSURL*url = [item valueForProperty:MPMediaItemPropertyAssetURL]; 它告诉我,URL为空. (2认同)

nvr*_*rst 16

只是想说,在iOS 6和7中,AVAudioPlayer可以直接从iPod播放文件URL,而无需像Art建议那样将音频数据复制到您的应用目录中.

- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) collection {


    MPMediaItem *item = [[collection items] objectAtIndex:0];
    NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];

    // Play the item using AVPlayer
    self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
    [self.avAudioPlayer play];
}
Run Code Online (Sandbox Code Playgroud)

  • 有人可以验证AVAudioPlayer是否可以真正播放iPod库中的歌曲?现在,在MPMusicPlayerController上弃用setVolume变得更加重要. (3认同)
  • 我使用AVAudioPlayer在iOS 6和7中播放iPod歌曲.它有效. (2认同)

dil*_*zek 5

我想补充(我不能发表评论,但SO),这看上去好像是在iOS 8的,也许之前,存储在iCloud中的歌曲不具备的属性值assetURL和回报null[npItem valueForProperty:MPMediaItemPropertyAssetURL]

这是一个示例输出:

MPMediaItem *npItem = self.musicPlayerController.nowPlayingItem;
NSLog(@"Song Title: %@\n assetURL: %@\n Cloud Item: %d", npItem.title, [npItem valueForProperty:MPMediaItemPropertyAssetURL], npItem.cloudItem)


// Log Output
Song Title: Time We Had
assetURL: (null)
Cloud Item: 1

Song Title: The Quiet
assetURL: ipod-library://item/item.m4a?id=1529654720874100371
Cloud Item: 0
Run Code Online (Sandbox Code Playgroud)