MPMoviePlayerController在下载和写入此文件时播放本地mp3文件

时间:2016-03-10 04:40:36

标签: ios objective-c streaming local-storage mpmovieplayercontroller

我正在音乐项目中工作,现在我的缓存流存在很大问题。我做了如下解决方案:

在使用URL播放音乐之前,我下载此文件并保存到临时目录,当下载过程达到约20%时,App会播放带有此本地文件的音乐,因此音乐正在播放而mp3文件正在下载80 %left。

下载完成后100%,但MPMoviePlayerController可以播放到20%(不是100%)。

请告诉我如何解决此问题?

谢谢!

我更新了我的代码:

- (void)playWithURL:(NSURL *)url{
    [self cacheSong:self.nowPlayingItem progress:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
    } success:^(NSString *filePath) {
        if (filePath) {
            [self playWithURL:[NSURL fileURLWithPath:filePath isDirectory:NO]];
        }
    } failure:^(NSError *error) {
    }];
}

- (void)cacheSong:(SongObj *)songObj progress:(void (^)(NSUInteger receivedBytes, long long totalReceivedBytes, long long totalExpectedBytes))progress success:(void (^)(NSString *filePath))success failure:(void (^)(NSError *error))failure{

    NSString *path = [FCFileManager pathForTemporaryDirectory];
    path = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Cache/%@.mp3", songObj.key.description]];
    BOOL created = [FCFileManager existsItemAtPath:path];
    if (created) {
        success(path);
        return;
    }
    created = [FCFileManager createFileAtPath:path overwrite:YES];
    if (!created) {
        return;
    }

    __block BOOL sent = NO;
    NSURLRequest *request = [NSURLRequest requestWithURL: [NSURL URLWithString:songObj.streamUrl]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath: path append:YES];

    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead){
        double percen = (double)(totalBytesRead * 100)/(double)totalBytesExpectedToRead;
        NSLog(@"percen = %lf", percen);
        if (percen >= 10 && !sent) {
            sent = YES;
            success(path);
        }
         progress(bytesRead, totalBytesRead, totalBytesExpectedToRead);
     }];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        if (!sent) {
            sent = YES;
            success(path);
        }
     }failure:^(AFHTTPRequestOperation *operation, NSError *error){
         failure(error);
     }];

    [operation start];
}

0 个答案:

没有答案