【问题标题】:How to play video from NSData如何从 NSData 播放视频
【发布时间】:2011-02-17 08:32:49
【问题描述】:

我想知道是否可以使用 MPMoviePlayerController 从 NSData 对象播放视频。

【问题讨论】:

标签: mpmovieplayercontroller nsdata playback


【解决方案1】:

Ben 的答案在模拟器上完美运行,但无法在设备上运行,您无法在设备上的任何位置书写。检查下面的代码

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myMove.mp4"];

    [videoData writeToFile:path atomically:YES];
    NSURL *moveUrl = [NSURL fileURLWithPath:path];
    player = [[MPMoviePlayerController alloc]init];
    [player setContentURL:moveUrl];
    player.view.frame = viewPlayer.bounds;
    [viewPlayer addSubview:player.view];
    [player play];

【讨论】:

  • 操作!我不敢相信我刚刚回答了一个一年前的问题......:)
  • 我想知道是否有任何方法可以在不写入文件的情况下做到这一点?
  • [[NSFileManager defaultManager] createFileAtPath:videoPath contents:videoData attributes:nil];
【解决方案2】:

据我所知,这是不可能的。如果数据来自您的数据库,您可以将其保存到临时文件中并播放吗?

【讨论】:

  • 是的,但我想避免这种情况... ;) 我现在正在尝试使用 QTKit 框架来执行此操作...
【解决方案3】:

在这种情况下最好使用 NSFileManager 而不是 writeToFile

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myMove.mp4"];

[[NSFileManager defaultManager] createFileAtPath:path contents:videoData attributes:nil];

NSURL *moveUrl = [NSURL fileURLWithPath:path];
player = [[MPMoviePlayerController alloc]init];
[player setContentURL:moveUrl];
player.view.frame = viewPlayer.bounds;
[viewPlayer addSubview:player.view];
[player play];

【讨论】:

  • 使用 createFileAtPath 与 writeToFile 有什么优势?
【解决方案4】:
  1. 创建一个具有 NSData 类型的文件,例如,如果您的 NSData 是 mp4 类型,则创建一个具有该类型的文件 - 例如 - “myMove.mp4”

  2. 将文件复制到您的应用资源中

  3. 添加此代码

    NSData *mediaData; //your data    
    NSString *movePath=[[NSBundle mainBundle] pathForResource:@"myMove" ofType:@"mp4"];         
    [mediaData writeToFile:movePath atomically:YES];        
    NSURL *moveUrl= [NSURL fileURLWithPath:movePath];    
    MPMoviePlayerController *movePlayer=[[MPMoviePlayerController alloc]init];          
    [movePlayer setContentURL:moveUrl]; 
    [movePlayer play];
    

【讨论】:

  • 这在设备上不起作用,您无法在设备上的任何位置写入文件。在下面查看我的答案..
猜你喜欢
  • 1970-01-01
  • 2020-09-07
  • 1970-01-01
  • 2020-05-02
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
  • 1970-01-01
相关资源
最近更新 更多