我发现您的代码至少存在一个问题,即以下行
NSURL *fileURL = [NSURL URLWithString:filePath];
它尝试使用本地文件路径创建 URL。它可能会返回零。你应该使用:
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
现在,即使这样,您的代码也无法运行(我尝试过并得到了与您相同的错误)。我自己不太使用 AVAudioPlayer 所以我不知道为什么会发生你的具体错误。
但是,我确实使用您的代码尝试了一个非常小的示例,并且我能够正确播放 MP3。您可以使用 AVAudioPlayer 的 initWithData 构造函数,而不是将数据下载到文件并从文件加载 AVAudioPlayer:
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfURL:audioURL] error:&error];
假设 audioURL 有效,这对我来说效果很好。我指向我的服务器上的一个 mp4 进行测试。
因此,用这个 initWithData 重写代码会给出:
- (IBAction)play:(UIButton *)sender {
dispatch_queue_t downloadQueue = dispatch_queue_create("audio data downloader", NULL);
dispatch_async(downloadQueue, ^{
NSURL *audioURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/%@.mp3", FONYK_FILES_URL, [self.voicenote valueForKeyPath:@"Fonyker.fonykid"], [self.voicenote valueForKeyPath:@"Voicenote.vnid"]]];
NSData *audioData = [NSData dataWithContentsOfURL:audioURL];
dispatch_async(dispatch_get_main_queue(), ^{
NSError *error = nil;
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error];
NSLog(@"%@", error);
audioPlayer.delegate = self;
[audioPlayer play];
});
});
}
最后一点:您在开始播放之前下载整个文件,这可能需要一段时间并消耗大量堆(或存储空间,如果您要将其保存在文件中)
如果要进行流式传输,可以使用 MPMoviePlayerController,但不要将视图附加到视图层次结构中。这样,您将只拥有音频,而不会更改应用程序的任何视觉效果。
一个例子是:
NSURL *audioURL = [NSURL URLWithString:@"MY_MP3_URL"];
MPMoviePlayerController* player = [[MPMoviePlayerController alloc] initWithContentURL:audioURL];
[player play];
同样,在我这边,在模拟器中,它工作得很好。
不要忘记释放播放器。您还可以注册代表以获取重要通知。
详细信息在这里:http://developer.apple.com/library/ios/#documentation/media player/reference/MPMoviePlayerController Class/Reference/Reference.html http://developer.apple.com/library/ios/#documentation/mediaplayer/reference/MPMoviePlayerController_Class/Reference/Reference.html