播放下载的(非流式)视频

时间:2014-01-16 16:44:49

标签: ios objective-c

我需要从服务器下载,保存和播放视频文件。我的下载和保存技术似乎工作,但我无法播放视频。视频在服务器上的路径是正确的,这项技术也适用于下载,保存和查看png。此外,MPMoviePlayerController似乎找到了文件,它只是无法播放它。我得到一个视频应该是的黑色区域。

任何帮助将不胜感激。下面是我的代码(目标:iOS 6.1,xCode 5)。

//Downloading & Saving
-(void)downloadFileAtPath:(NSString *)path
{
    NSURL *url                  = [NSURL URLWithString:path];     
     NSMutableURLRequest *req    = [NSMutableURLRequest requestWithURL:url];
     NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    [connection start];
}

-(void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
    //NSLog(@"%s", __PRETTY_FUNCTION__);
    [[NSFileManager defaultManager] createFileAtPath:pathForCurrentFile contents:nil attributes:nil];
    currentFile = [NSFileHandle fileHandleForUpdatingAtPath:pathForCurrentFile];
    if (currentFile)
    {
    [currentFile seekToEndOfFile];
    }
}

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    //NSLog(@"%s", __PRETTY_FUNCTION__);
    if( currentFile != nil){
        if (currentFile)  {
            [currentFile seekToEndOfFile];
        }
        [currentFile writeData:data];
    }
}

-(void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"%s, %@", __PRETTY_FUNCTION__, error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [currentFile closeFile];
}

以下是播放代码

    //Playback
    NSString *loopFilePath = [[self applicationDocumentsDirectory].path stringByAppendingPathComponent:vidFileName];

    NSURL *vidURL = [NSURL fileURLWithPath:vidFilePath];

    self.vidController = [[MPMoviePlayerController alloc] initWithContentURL:vidURL];
    self.vidController.view.frame = CGRectMake(0, 0, 640, 480);
    self.vidController.controlStyle = MPMovieControlStyleDefault;
    [self.view addSubview:self.vidController.view];
    [self.vidController prepareToPlay];
    [self.vidController play];

2 个答案:

答案 0 :(得分:0)

这:

[self.view addSubview:self.loopVidController.view];

应该是这样的:

[self.view addSubview:self.vidController.view];

试试这个:

self.vidController = [[MPMoviePlayerController alloc] initWithContentURL:vidURL];
self.vidController.controlStyle = MPMovieControlStyleDefault;
self.vidController.shouldAutoplay = YES;
[self.view addSubview:self.vidController.view];
[self.vidController setFullscreen:YES animated:YES];

答案 1 :(得分:0)

解决方案:保存并播放视频文件时,必须附加文件扩展名。在这种情况下.mov。对.png文件使用相同的技术时,不需要扩展名。