AVAudioPlayer 初始化与 web URL 崩溃

AVAudioPlayer initialization with web URL crashes

我在服务器上有一个声音文件,我尝试在设备上播放它。

使用此代码:

NSURL audioURL = [NSURL URLWithString:@"http://..."];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&error]

因错误而崩溃:

Description of exception being thrown: '-[NSTaggedPointerString getCharacters:range:]: Range {0, 12} out of bounds; string length 5

url 的长度为 73

首先,为什么它崩溃而不是填充我的 error 对象?

如果我使用此代码:

NSURL audioURL = [NSURL URLWithString:@"http://..."];
NSData *audioData = [NSData dataWithContentsOfURL:audioURL];
NSError *error;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error]

有效。

看方法名,好像都是做同样的事情,为什么第一个方法不行呢? 阅读 AVAudioPlayer init 方法的文档没有发现与此问题相关的任何内容。

您正在流式传输您的音频文件吗? AVAudioPlayer 无法从 URL 流式传输。您可以将它与存储在设备上的文件一起使用。 如果你想从 URL 流式传输你的文件,你需要使用 AVPlayer 以下代码:

AVPlayerItem *item = [AVPlayerItem playerItemWithURL: audioURL];
AVPlayer *myAVPlayer = [AVPlayer playerWithPlayerItem: item];

编辑

当您要将 AVAudioPlayer 与 URL 一起使用时,您需要像这样展示您的 URL:

NSString *backgroundMusicPath = [[NSBundle mainBundle] pathForResource:@"myMusic" ofType:@"mp3"];
NSURL *backgroundMusicURL = [NSURL fileURLWithPath:backgroundMusicPath];

取自here

希望对您有所帮助