无法在 AVAudioPlayer 中通过 URL 播放声音

Unable to play sound via URL in AVAudioPlayer

我已经查看并应用了 Whosebug 上提供的几乎所有解决方案,但它对我不起作用。这是我的代码:

NSString *path = [NSString stringWithFormat:@"http://www.schillmania.com/projects/soundmanager2/demo/_mp3/rain.mp3"];
        NSURL *soundUrl = [NSURL fileURLWithPath:path];

        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];

        [_player play];

根据类似问题的其他答案,我也做了@property (strong, nonatomic) AVAudioPlayer *player;,但还是不行。我做错了什么?

根据评论我也试过这个:

NSURL *url = [[NSURL alloc]initWithString:@"http://www.schillmania.com/projects/soundmanager2/demo/_mp3/rain.mp3"];
        AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:url];
        AVPlayer *pla = [[AVPlayer alloc]initWithPlayerItem:item];
        [pla play];

但是还是没有播放!

正如@paiv 所说,AVAudioPlayer 不会从互联网上下载您的文件。 NSURLs 用于本地文件和 Internet 资源,在这种情况下,声音必须是本地文件。您需要先下载文件,然后再播放。您需要下载文件(可能使用 NSURLSessionNSURLSessionDownloadTask),然后在文件下载完成后播放声音。

编辑:

正如@Sneak 在他下面的评论中指出的那样,AVPlayer 能够从网络流式传输音频,尽管实际上我自己从未使用过该功能。

我以前用过这个,对我来说效果很好

https://github.com/tumtumtum/StreamingKit