ios swift avfoundation avplayerviewcontroller avkit

ios - avplayer swift



Cómo reproducir video con AVPlayerViewController(AVKit) en Swift (11)

¿Cómo se reproduce un video con AV Kit Player View Controller en Swift?

override func viewDidLoad() { super.viewDidLoad() let videoURLWithPath = "http://****/5.m3u8" let videoURL = NSURL(string: videoURLWithPath) playerViewController = AVPlayerViewController() dispatch_async(dispatch_get_main_queue()) { self.playerViewController?.player = AVPlayer.playerWithURL(videoURL) as AVPlayer } }


C objetivo

Esto solo funciona en Xcode 7

Vaya al archivo .h e importe AVKit/AVKit.h y AVFoundation/AVFoundation.h . Luego vaya al archivo .m y agregue este código:

NSURL *url=[[NSBundle mainBundle]URLForResource:@"arreg" withExtension:@"mp4"]; AVPlayer *video=[AVPlayer playerWithURL:url]; AVPlayerViewController *controller=[[AVPlayerViewController alloc]init]; controller.player=video; [self.view addSubview:controller.view]; controller.view.frame=self.view.frame; [self addChildViewController:controller]; [video play];


¿Un error (?!) en iOS10 / Swift3 / Xcode 8?

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){ let playerItem = AVPlayerItem(url: url) let player = AVPlayer(playerItem: playerItem) let playerLayer = AVPlayerLayer(player: player) playerLayer.frame=CGRect(x: 10, y: 10, width: 300, height: 300) self.view.layer.addSublayer(playerLayer) }

no funciona (vaciar rect ...)

esto funciona:

if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){ let player = AVPlayer(url: url) let controller=AVPlayerViewController() controller.player=player controller.view.frame = self.view.frame self.view.addSubview(controller.view) self.addChildViewController(controller) player.play() }

Misma URL ...


Prueba esto

var player:AVPlayer! var avPlayerLayer:AVPlayerLayer = AVPlayerLayer(player: player) avPlayerLayer.frame = CGRectMake(your frame) self.view.layer .addSublayer(avPlayerLayer) var steamingURL:NSURL = NSURL(string:playerURL) player = AVPlayer(URL: steamingURL) player.play()


Prueba esto, definitivamente funciona para Swift 2.0

let player = AVPlayer(URL: url) let playerController = AVPlayerViewController() playerController.player = player self.addChildViewController(playerController) self.view.addSubview(playerController.view) playerController.view.frame = self.view.frame player.play()


Swift 3:

import UIKit import AVKit import AVFoundation class ViewController: UIViewController { @IBOutlet weak var viewPlay: UIView! var player : AVPlayer? override func viewDidLoad() { super.viewDidLoad() let url : URL = URL(string: "http://static.videokart.ir/clip/100/480.mp4")! player = AVPlayer(url: url) let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = self.viewPlay.bounds self.viewPlay.layer.addSublayer(playerLayer) } @IBAction func play(_ sender: Any) { player?.play() } @IBAction func stop(_ sender: Any) { player?.pause() } }


Esto funcionó para mí en Swift 5

Acabo de agregar un video de muestra al proyecto desde Videos de muestra

Se agregaron botones de acción para reproducir videos del sitio web y locales con el siguiente ejemplo de código rápido

import UIKit import AVKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play } @IBAction func playWebVideo(_ sender: Any) { guard let url = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") else { return } // Create an AVPlayer, passing it the HTTP Live Streaming URL. let player = AVPlayer(url: url) let controller = AVPlayerViewController() controller.player = player present(controller, animated: true) { player.play() } } @IBAction func playLocalVideo(_ sender: Any) { guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else { return } let videoURL = NSURL(fileURLWithPath: path) // Create an AVPlayer, passing it the local video url path let player = AVPlayer(url: videoURL as URL) let controller = AVPlayerViewController() controller.player = player present(controller, animated: true) { player.play() } } }


Código fuente completo de Swift 3.0:

import UIKit import AVKit import AVFoundation class ViewController: UIViewController,AVPlayerViewControllerDelegate { var playerController = AVPlayerViewController() @IBAction func Play(_ sender: Any) { let path = Bundle.main.path(forResource: "video", ofType: "mp4") let url = NSURL(fileURLWithPath: path!) let player = AVPlayer(url:url as URL) playerController = AVPlayerViewController() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.didfinishplaying(note:)),name:NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem) playerController.player = player playerController.allowsPictureInPicturePlayback = true playerController.delegate = self playerController.player?.play() self.present(playerController,animated:true,completion:nil) } func didfinishplaying(note : NSNotification) { playerController.dismiss(animated: true,completion: nil) let alertview = UIAlertController(title:"finished",message:"video finished",preferredStyle: .alert) alertview.addAction(UIAlertAction(title:"Ok",style: .default, handler: nil)) self.present(alertview,animated:true,completion: nil) } func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) { let currentviewController = navigationController?.visibleViewController if currentviewController != playerViewController { currentviewController?.present(playerViewController,animated: true,completion:nil) } } }


Swift 3.x - 5.x

Necesario: importar AVKit , importar AVFoundation

El marco de AVFoundation es necesario incluso si usa AVPlayer

Si desea usar AVPlayerViewController :

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") let player = AVPlayer(url: videoURL!) let playerViewController = AVPlayerViewController() playerViewController.player = player self.present(playerViewController, animated: true) { playerViewController.player!.play() }

o simplemente AVPlayer :

let videoURL = URL(string: "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4") let player = AVPlayer(url: videoURL!) let playerLayer = AVPlayerLayer(player: player) playerLayer.frame = self.view.bounds self.view.layer.addSublayer(playerLayer) player.play()

Es mejor poner este código en el método: anular func viewDidAppear (_ animated: Bool) o en algún lugar después.

C objetivo

AVPlayerViewController :

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"]; AVPlayer *player = [AVPlayer playerWithURL:videoURL]; AVPlayerViewController *playerViewController = [AVPlayerViewController new]; playerViewController.player = player; [self presentViewController:playerViewController animated:YES completion:^{ [playerViewController.player play]; }];

o simplemente AVPlayer :

NSURL *videoURL = [NSURL URLWithString:@"https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"]; AVPlayer *player = [AVPlayer playerWithURL:videoURL]; AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player]; playerLayer.frame = self.view.bounds; [self.view.layer addSublayer:playerLayer]; [player play];


Swift 5

@IBAction func buttonPressed(_ sender: Any) { let videoURL = course.introductionVideoURL let player = AVPlayer(url: videoURL) let playerViewController = AVPlayerViewController() playerViewController.player = player present(playerViewController, animated: true, completion: { playerViewController.player!.play() })

// aquí el curso incluye un archivo de modelo, dentro de él he dado la url, así que llamo a la función del modelo usando la función del curso.

// también IntroductionVideoUrl es una URL que he declarado dentro del modelo.

var introductionVideoURL: URL

También, alternativamente, puede usar el siguiente código en lugar de llamar a la función desde el modelo

Reemplace este código

let videoURL = course.introductionVideoURL

con

guard let videoURL = URL(string: "https://something.mp4) else { return


Usando MPMoviePlayerController:

import UIKit import MediaPlayer class ViewController: UIViewController { var streamPlayer : MPMoviePlayerController = MPMoviePlayerController(contentURL: NSURL(string:"video url here")) override func viewDidLoad() { super.viewDidLoad() streamPlayer.view.frame = self.view.bounds self.view.addSubview(streamPlayer.view) streamPlayer.fullscreen = true // Play the movie! streamPlayer.play() } }

Usando AVPlayer:

import AVFoundation var playerItem:AVPlayerItem? var player:AVPlayer? override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "url of the audio or video") playerItem = AVPlayerItem(URL: url!) player=AVPlayer(playerItem: playerItem!) let playerLayer=AVPlayerLayer(player: player!) playerLayer.frame=CGRectMake(0, 0, 300, 50) self.view.layer.addSublayer(playerLayer) }

Tengo un botón de reproducción para manejar el toque del botón.

playButton.addTarget(self, action: "playButtonTapped:", forControlEvents: .TouchUpInside) func playButtonTapped(sender: AnyObject) { if player?.rate == 0 { player!.play() playButton.setImage(UIImage(named: "player_control_pause_50px.png"), forState: UIControlState.Normal) } else { player!.pause() playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal) } }

He agregado un observador que escucha AVPlayerItemDidPlayToEndTimeNotification.

override func viewWillAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlaying:", name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem) } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) }

Cuando finalice la reproducción de video / audio, restablezca la imagen del botón y la notificación

func finishedPlaying(myNotification:NSNotification) { playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal) let stopedPlayerItem: AVPlayerItem = myNotification.object as! AVPlayerItem stopedPlayerItem.seekToTime(kCMTimeZero) }


let videoUrl = //URL: Your Video URL //Create player first using your URL let yourplayer = AVPlayer(url: videoUrl) //Create player controller and set it’s player let playerController = AVPlayerViewController() playerController.player = yourplayer //Final step To present controller with player in your view controller present(playerController, animated: true, completion: { playerController.player!.play() })