ios - 使用 initWithContentsOfURL 使用 iPod 歌曲 URL 初始化 AVAudioPlayer

标签 ios background avaudioplayer initwithcontentsofurl

我知道可以使用 AVPlayer 播放 iPod 歌曲,但我不知道如何使用 initWithContentsOfURL 使用 iPod 歌曲 URL 初始化 AVAudioPlayer。当我尝试时,AVAudioPlayer 在初始化时返回 NULL。

我需要使用 AVAudioPlayer 因为当我的应用在后台运行时我需要使用它的委托(delegate)方法 audioPlayerDidFinishPlaying 进行进一步处理(即 AVAudioPlayer 委托(delegate)方法 audioPlayerDidFinishPlaying 如果应用程序在后台运行,则会调用。但是 AVPlayer 不提供委托(delegate)方法,因此您只能使用不运行的通知在后台)。

以下代码用于使用 AVPlayer 播放 iPod 歌曲。

- (void)viewDidLoad {

    [super viewDidLoad];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSError *error = nil;

    [session setActive:YES error:&error];
    MPMediaQuery *query = [MPMediaQuery songsQuery];
    NSArray *collection = [query items];
    MPMediaItem *item = [collection objectAtIndex:0];
    NSLog(@"%@",[item valueForProperty:MPMediaItemPropertyTitle]);
    NSURL *url = [item valueForProperty:MPMediaItemPropertyAssetURL];
    AVPlayer *player = [[AVPlayer alloc]initWithURL:url];   // <-- Line to Replace
    [player play];
}

这很好用。但是,如果我用以下内容替换倒数第二行:

    AVAudioPlayer *player = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];

调用 initWithContentsOfURL 返回 NULL。

关于为什么当我使用 AVAudioPlayer 时返回 NULL,而当我使用 AVPlayer 时返回初始化的播放器有什么想法吗?

根据技术问答http://developer.apple.com/library/ios/#qa/qa1634/_index.html , "与 initWithContentsOfURL: 一起使用的 URL 必须是文件 URL (file://)。即本地路径。"

当我在我的 iPod 库中获取歌曲的 url 时,路径是:

ipod-library://item/item.mp3?id=-4017276016911605928

你会说我的 iPod 库的这条路径不被视为“本地路径”,还是你会认为它是 initWithContentsOfURL 返回 NULL 的错误?

有什么想法吗?

最佳答案

你已经回答了你自己的问题,因为据我所知,它是对 AVAudioPlayer 很重要的 url 路径,它必须是本地的包。有一个将 AVPlayer 与通知一起使用的示例,在 AVPlayerDemo 中搜索 playerItemDidReachEnd 但我无法告诉您它是在后台运行还是在前台运行。

关于ios - 使用 initWithContentsOfURL 使用 iPod 歌曲 URL 初始化 AVAudioPlayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8691109/

相关文章:

ios - UIViewController 中的 Swift 动态 TableView

javascript - #import 如何在 iOS 的 UI 自动化中工作?

css - 具有多个背景的线性渐变

ios - 设置 iOS MPMusicPlayerController 相对于 AVAudioPlayer 的音量

iOS 画线时用两个箭头和起点终点同时手指触摸终点并从起点或终点旋转

ios - 后台任务和后台正确获取有什么区别?

css - 多个背景与 CSS

android - 更改背景图片 - Android

ios - iPhone 7 Plus AVPlayer 周围有边框(白色颜色不匹配)

iOS:当应用程序不再位于前台时重置音频播放器