3

我目前正在使用以下代码使用 AVPlayer 播放 mp3

    NSString *title = [[NSString alloc] initWithFormat:@"http://.......com/%@", mp3File];
    NSURL *url = [[NSURL alloc] initWithString:title];
    AVPlayerItem *anItem = [AVPlayerItem playerItemWithURL:url];


    player = [AVPlayer playerWithPlayerItem:anItem];

    [player play];

但是我也想存储下载的文件,因此后续播放不需要再次下载文件。为此,我使用以下

     NSString  *path = [NSHomeDirectory() stringByAppendingPathComponent:[@"Documents/" stringByAppendingString:surahAyah]];

     if (![[NSFileManager defaultManager] fileExistsAtPath:path])
     {
        NSString *title = [[NSString alloc] initWithFormat:@"http://.......com/%@", mp3File];
        NSURL *url = [[NSURL alloc] initWithString:title];

        NSData *dbFile = [[NSData alloc] initWithContentsOfURL:url];
        [dbFile writeToFile:path atomically:YES];
     }

合并上述内容并使用缓存的最佳实践是什么?AVPlayerItem 并存储它而不是重新调用来下载和保存文件?

MP3 文件大小约为 100KB,所以我不太担心下载进度。

4

1 回答 1

3

我已经成功地使用了很棒的 AFNetworking 库来完成这项工作

  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

  operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

  [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];


    [operation start];
于 2012-09-25T18:35:45.670 回答