如何从文档目录中播放视频(按名称)?

时间:2013-08-01 05:18:57

标签: iphone ios objective-c video

在我的应用程序中,我将我的视频存储在名称为'video2.MOV'的文档目录中,我想播放它。

此问题是我无法从文档目录中获取此视频(名称为'video2.MOV'

我的代码:

-(void)playVideo:(NSTimer *)theTimer
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"video2.MOV"];
    NSLog(@"filePath - %@",filePath);

    NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
    NSLog(@"contentPath - %@",content);

    MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:content]];
    [[CCDirector sharedDirector] presentMoviePlayerViewControllerAnimated:videoPlayerView];
    [videoPlayerView.moviePlayer play];
}

在控制台中,每次 contentPath NULL时,我都可能无法播放视频。

在这里,我的错误是什么。请给我关于这个问题的建议。

2 个答案:

答案 0 :(得分:1)

试试这个:

- (NSString*)GetDocumentFilePath:(NSString*)filename
{
    NSLog(@"%@",filename);
    // NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
    NSString *documentsDirectory = [paths objectAtIndex:0]; //2
    NSString* file = [[NSString alloc]initWithFormat:@"%@",filename];
    NSString* path = [documentsDirectory stringByAppendingPathComponent:file];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath: path]) //4
    {
        //NSString *bundle = [[NSBundle mainBundle] pathForResource:filename ofType:@"plist"]; //5

        //[fileManager copyItemAtPath:bundle toPath:path error:&error]; //6
    }  

    return path;
}

并获取如下文件路径:

 NSURL *URL = [NSURL fileURLWithPath:[self GetDoucmentPath:path]];


MPMoviePlayerController* theMovie=[[MPMoviePlayerController alloc] initWithContentURL:pptURL];
    theMovie.scalingMode=MPMovieScalingModeAspectFill;

    theMovie.view.frame = CGRectMake(60, 20, 700, 500);
    theMovie.view.center = self.view.center;

    //[self.view addSubview:theMovie.view];

    // Register for the playback finished notification. 

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(onStop) 
                                                 name:MPMoviePlayerPlaybackDidFinishNotification 
                                               object:theMovie];

    // Movie playback is asynchronous, so this method returns immediately. 

    [self.view addSubview:theMovie.view];
    [theMovie play];

希望它能帮助!!

答案 1 :(得分:0)

而不是使用content使用filePath来取代电影文件:

 MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:filePath]];