在Objective-C中播放视频

时间:2017-12-11 09:12:20

标签: ios objective-c

我有一个ViewController,我正在尝试播放视频。视频在我的项目中本地添加,但是当我打开ViewController时,它显示任何错误和应用程序崩溃,错误就是这样,

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'

我的代码就是这个,

NSString *path=[[NSBundle mainBundle]pathForResource:@"Video" ofType:@"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
AVPlayer *player = [AVPlayer playerWithURL:url];
AVPlayerViewController *controller = [[AVPlayerViewController alloc]init];
controller.view.frame = self.view.bounds;
[self.view addSubview:controller.view];
[player play];

2 个答案:

答案 0 :(得分:0)

试试这个:

ViewController.h

#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>

@interface ViewController : UIViewController
@property (strong, nonatomic) AVPlayerViewController *playerViewController;

@end

ViewController.m

#import "ViewController.h"

@interface ViewController (){
NSURL *vedioURL;
}

@end

@implementation ViewController
@synthesize playerViewController;

- (void)viewDidLoad {
 [super viewDidLoad];


  NSString *fullpath = [[self documentsDirectory] stringByAppendingPathComponent:@"yourdate.3gp"];
  vedioURL =[NSURL fileURLWithPath:fullpath];
  AVPlayerItem* playerItem = [AVPlayerItem playerItemWithURL:vedioURL];
  AVPlayer* playVideo = [[AVPlayer alloc] initWithPlayerItem:playerItem];
  playerViewController = [[AVPlayerViewController alloc] init];
  playerViewController.player = playVideo;
  playerViewController.player.volume = 0;
  playerViewController.view.frame = self.view.bounds;
  [self.view addSubview:playerViewController.view];
  [playVideo play];

}


-(NSString *)documentsDirectory{
 NSArray *paths = 
 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 return documentsDirectory;
}

答案 1 :(得分:0)

确保将本地视频添加到目标成员资格中。选择

  

视频 - &gt;显示文件Inspector-&gt;目标会员资格 - &gt;启用。

并添加以下代码行:

{{1}}