How to add AVPlayer to UIView in ViewController

I my UIViewControllerI have a way out to UIViewwhere I would like to show the video using external links. In this case, I am trying to create AVPlayerLayerand add it to my UIViewoutput.

My code is as follows:

class VievController: UICollectionViewController {
    @IBOutlet weak var playerView: UIView!

    override func viewDidLoad(){
            let playerItem = AVPlayerItem(URL: NSURL(string: ("https://www.youtube.com/watch?v=_yE_XgoWBso"))!)
            let avPlayer = AVPlayer(playerItem: playerItem)
            let playerLayer = AVPlayerLayer(player: avPlayer)
            playerLayer.frame = playerView.bounds
            playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            playerView.layer.addSublayer(playerLayer)
            avPlayer.play()
    }
}//end class

I don’t know why I don’t see the video in my UIViewoutlet - nothing happened. Do you have any suggestion that I should fix it?

+4
source share
3 answers
    let url = NSBundle.mainBundle().URLForResource("ding.mp3", withExtension: nil)
    guard let newURL = url else {
         print("Could not find file:")
        return
    }
    do {

        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = 0
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()

    } catch let error as NSError {
        //print(error.description)
    }

You need to import avfoundation infrastructure and then use this code above

+1
source

, AVPlayer YouTube, Vimeo .. UIWebView.

0
Below code help you to solve the issue

Adjust the frame according to your needs

- (void)viewDidLoad
{
   [super viewDidLoad];
   NSError *setCategoryError = nil;
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error: &setCategoryError];
  NSString *urlString=[NSString stringWithFormat:@"%@",@"http://www.youtube.com/watch?v=zPP6lXaL7KA&feature=youtube_gdata_player"];
  AVAsset *asset = [AVAsset assetWithURL:[NSURL urlWithString:urlString]];
  avPlayerItem = [[AVPlayerItem alloc]initWithAsset:asset];
  self.songPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
  self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer: self.songPlayer];
  self.avPlayerLayer.frame = self.view.layer.bounds;
  UIView *newView = [[UIView alloc] initWithFrame:self.view.bounds];
  [newView.layer addSublayer:avPlayerLayer];
  [self.view addSubview:newView];
  [ self.songPlayer play];
}
-1

All Articles