使用AVPlayer播放和下载MP3文件

时间:2012-09-12 21:02:49

标签: ios avplayer

我目前正在使用以下代码播放带有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,所以我不太担心下载进度。

1 个答案:

答案 0 :(得分: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];