I'm trying to play a video usingso I got some code from a tutorial but it won't work.
Here's the code I use :
- (void) viewDidAppear:(BOOL)animated
{
avAsset = [AVAsset assetWithURL:[NSURL URLWithString:filePath]];
avPlayerItem =[avPlayerItem initWithAsset:avAsset];
avPlayer = [AVPlayer playerWithPlayerItem:avPlayerItem];
avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:avPlayer];
[avPlayerLayer setFrame:self.view.frame];
[self.view.layer addSublayer:avPlayerLayer];
[avPlayer seekToTime:kCMTimeZero];
[avPlayer play];
}
I don't know what's wrong it doesn't give ny errors it just gives black screen. Thanks.
Thanks s1mon and matt for your help.
Here's the new code it might help someone:
- (void) viewDidAppear:(BOOL)animated
{
avAsset = [AVAsset assetWithURL:[NSURL fileURLWithPath:filePath]];
avPlayerItem =[[AVPlayerItem alloc]initWithAsset:avAsset];
avPlayer = [[AVPlayer alloc]initWithPlayerItem:avPlayerItem];
avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:avPlayer];
[avPlayerLayer setFrame:self.view.frame];
[self.view.layer addSublayer:avPlayerLayer];
//[avPlayerLayer setBackgroundColor:[[UIColor redColor]CGColor]];
[avPlayer seekToTime:kCMTimeZero];
[avPlayer play];
}
Thank you.
This might not be the actual problem, but this code is certainly wrong:
[NSURL URLWithString:filePath]
First of all, try not to start with a file path; start with a file URL. That way, there is no conversion needed. But if you must perform a conversion from a file path to a URL, use fileURLWithPath:isDirectory:
. A file URL is a special kind of animal and you must ask for one specifically when you are converting from a path.
I think you forgot to create an instance of AVPlayerItem
in this line:
avPlayerItem =[avPlayerItem initWithAsset:avAsset];
This just sends initWithAsset:
to avPlayerItem
(which is probably nil when this method is called). Try changing it to instantiate an new AVPlayerItem
which you can then assign to avPlayerItem
, like this:
avPlayerItem = [[AVPlayerItem alloc] initWithAsset:avAsset];
For those looking for a swift 2.0 version
, here is what worked for me. Cheers.
import Foundation
import UIKit
import AVKit
class VideoViewController: AVPlayerViewController {
override func viewDidAppear(animated: Bool) {
self.setupVideoPlayerView()
}
private func setupVideoPlayerView()
{
let path = "HTTP_VIDEO_URL_HERE"
let nsURL = NSURL(string: path)
let avAsset = AVAsset(URL: nsURL!)
let avPlayerItem = AVPlayerItem(asset: avAsset)
let avPlayer = AVPlayer(playerItem: avPlayerItem)
let avPlayerLayer = AVPlayerLayer(layer: avPlayer)
avPlayerLayer.frame = self.view.frame
self.view.layer.addSublayer(avPlayerLayer)
self.player = avPlayer
self.player!.seekToTime(kCMTimeZero)
self.player!.play()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With