为什么我的 AVAudioPlayer 不播放声音?

Why does my AVAudioPlayer not play sound?

我的目标是下载一个 .mp3 文件,将其字节保存在内存中,然后让播放器播放。我不想将文件存储在设备上。

我这样下载文件:

+(NSData*) downloadFile:(NSString*) urlString {
    NSURL *url = [NSURL URLWithString: urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:10];
    [request setHTTPMethod:@"GET"];

    NSHTTPURLResponse* response;
    NSError* error = nil;

    NSData* data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];

    return data;
}

这很好用。我可以在调试器和十六进制编辑器中看到实际的字节值,它们是相同的。

然后我希望按照 Apple 文档的建议使用 AVAudioPlayer 播放它们:

NSData *mp3Bytes = result_of_downloadFile;
NSError *error;

AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:mp3Bytes error:&error];
player.delegate = self;

BOOL success = [player prepareToPlay];
[player setVolume:1];
player.numberOfLoops = 1;
if (success) {
    NSLog(@"Play it, it takes %f seconds", [player duration]);
    BOOL playing = [player play];
    NSLog(@"Playing? %i", playing);

} else {
    NSLog(@"failed");
}

日志告诉我一切正常,prepareToPlay:成功,play:成功,但是没有声音。

这是在实际设备上,ipad mini with ios 8.2。它可以使用 ios 音乐应用播放音乐。

那么,我的播放代码不正确呢?

你试过增加[玩家setVolume:1]的价值吗?

您的 AVAudioPlayer 似乎超出范围并被释放。把它变成一个成员变量来延长它的生命周期。