如何在AVPlayer中播放NSData?

时间:2017-03-10 06:17:58

标签: objective-c avplayer

我已使用cognate poolid从AWS服务器下载了视频NSData。将NSData转换为AVPlayer后尝试在NSData中播放NSURL。但它没有播放。

在界面中,我已经定义了

@property (nonatomic, strong) AVPlayer *avPlayer;

这是代码

NSData *data = [UserProfileInfo getVideoData];
NSLog(@"%lu", (unsigned long)data.length);

NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
_avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:dataString]];

_avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
videoLayer.frame = videoPreviewView.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[videoPreviewView.layer addSublayer:videoLayer];
[videoPreviewView.layer setOpacity:1.0];
[_avPlayer play];

实际上我在这里获取数据,但是当我将其转换为NSString

NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

然后我在 dataString 中获得nil。 请有人帮忙。

1 个答案:

答案 0 :(得分:1)

您需要将NSDATA保存在文档目录中,并将其路径提供给AVPlayer进行播放。

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            NSString *myPathDocs = [documentsDirectory stringByAppendingPathComponent:@"myVideo.mp4"];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            BOOL isFileWriteComplete = [yourNSdata writeToFile:myPathDocs atomically:YES];
    if(isFileWriteComplete)
    {
_avPlayer = [AVPlayer playerWithURL:[NSURL URLWithString:myPathDocs]];
_avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;
AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:_avPlayer];
videoLayer.frame = videoPreviewView.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[videoPreviewView.layer addSublayer:videoLayer];
[videoPreviewView.layer setOpacity:1.0];
[_avPlayer play];
    }