如何在objective-c中播放视频

时间:2017-09-13 04:37:04

标签: ios objective-c iphone avplayer

我需要使用objective-c在Xcode中播放视频。我在Xcode中拖了一个mp4文件。并使用了代码:

NSString *filepath   =   [[NSBundle mainBundle] pathForResource:@"videoname" ofType:@"mp4"];
NSURL *fileURL = [NSURL fileURLWithPath:filepath];
self.avPlayer = [AVPlayer playerWithURL:fileURL];
self.avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone;

AVPlayerLayer *videoLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
videoLayer.frame = self.view.bounds;
videoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:videoLayer];

[self.avPlayer play];

但在文件路径中将错误显示为nil。

3 个答案:

答案 0 :(得分:0)

通过拖放添加项目时你应该注意以下事项

1)拖放到 XCode 时,您必须选中复选框复制项目(如果需要)

2)应使用当前目标检查右侧面板上的目标

答案 1 :(得分:0)

尝试

  NSString *videoPath = [[NSBundle mainBundle] pathForResource:@"videoname" ofType:@"mp4"];
  NSURL *streamURL = [NSURL fileURLWithPath:videoPath];
  MPMoviePlayerController *moviplayer =[[MPMoviePlayerController alloc] initWithContentURL:     streamURL];
  [moviplayer prepareToPlay];
  [moviplayer.view setFrame: self.view.bounds];
  [self.view addSubview: moviplayer.view];
  moviplayer.fullscreen = YES;
  moviplayer.shouldAutoplay = YES;
  moviplayer.repeatMode = MPMovieRepeatModeNone;
  moviplayer.movieSourceType = MPMovieSourceTypeFile;
  [moviplayer play]; 

答案 2 :(得分:0)

  1. 将视频文件拖放到项目中,必须选中复选框 如果需要,复制项目
  2. 还要在构建阶段复制捆绑包资源
  3. 中添加视频文件

    enter image description here