Cara memutar video dengan AVPlayerViewController (AVKit) di Swift

164

Bagaimana Anda memutar video dengan AV Kit Player View Controller di 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
        }
    }
orazz
sumber
Untuk menggunakan AVPlayer(tidak memiliki kontrol), lihat jawaban ini .
Suragch

Jawaban:

532

Swift 3.x - 5.x

Diperlukan: impor AVKit , impor AVFoundation

Kerangka AVFoundation diperlukan bahkan jika Anda menggunakan AVPlayer

Jika Anda ingin menggunakan 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()
}

atau hanya 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()

Lebih baik memasukkan kode ini ke dalam metode: override func viewDidAppear (_ animated: Bool) atau di suatu tempat setelahnya.


Objektif-C

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];
}];

atau hanya 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];
pkis
sumber
@pikis Terima kasih untuk contoh kode. Aneh, kami mencoba AVPlayerController seperti yang tertulis dan mendapatkan SIGABRT di: [self presentViewController: animasi playerViewController: YES completion: nil];
Praxiteles
@Praxiteles, ini berfungsi di iOS8 atau lebih baru, mungkin itu alasannya.
pkis
8
Juga diperlukan AVFoundation impor untuk saya
Rich Fox
1
@ Nick89, AVPlayer berfungsi dengan benar dengan tautan langsung, tetapi jika Anda perlu menggunakan layanan seperti YouTube, Vimeo, dll. (Yang memiliki tautan tidak langsung), Anda harus menggunakan perpustakaan atau SDK mereka sendiri. (mis. untuk YouTube: panduan ).
pkis
2
Urutan instruksi ini penting, saya juga perlu mengimpor AVKit
htafoya
30

Coba ini, pasti berhasil 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()  
Chetan Dobariya
sumber
1
Terima kasih. AddChildViewController membuatnya tertanam persis seperti yang saya inginkan. :)
SDW
1
Penanaman tidak bekerja dengan sempurna, tetapi bagaimana Anda menangani perubahan orientasi? Katakanlah pemain mengambil setengah layar dalam potret dan pengontrol tampilan hanya mendukung potret tetapi video dapat dilihat dalam potret seperti kebanyakan aplikasi lakukan .. youtube, vimeo, dll.
Abid Hussain
Catatan: addChildViewController diperlukan. Saya mencoba tanpa itu dan kemudian hampir berhasil - itu diputar sekali, itu mengembang ke layar penuh. Tapi itu tidak bisa diputar lagi, atau keluar dari mode layar penuh. Jadi pengontrol tampilan anak diperlukan.
n13
self.addChildViewController(playerController)sekarang self.addChild(playerController)fyi
Marquis103
12

Coba ini

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()
Ramesh
sumber
Ketika saya menjalankan kode ini saya mendapatkan controller tampilan kosong
orazz
@Oneperson Anda menyetel bingkai avPlayerLayer?
Ramesh
1
@Oneperson ok set avPlayerLayer.frame = CGRectMake (50,50,100,100)
Ramesh
code var player: AVPlayer! var playerItem: AVPlayerItem!; var avPlayerLayer: AVPlayerLayer = AVPlayerLayer (pemain: pemain) avPlayerLayer.frame = CGRectMake (50,50,100,100) self.view.layer .addSublayer (avPlayerLayer) biarkan videoURLWithPath = "http: //*****/45.m3u8" var steamingURL: NSURL = NSURL (string: videoURLWithPath) pemain = AVPlayer (URL: steamingURL) kode player.play ()
orazz
@Oneperson edge.tolkun.tv/45.m3u8 tidak berfungsi. dapatkah Anda memberikan url lengkap Anda
Ramesh
11

Swift 3.0 Kode sumber lengkap:

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)
                }


            }
    }
ronak patel
sumber
Halo ronak, terima kasih telah memperkenalkan pengamat dengan cepat untuk menangani akhir video !! Saya tidak berhasil membuatnya bekerja dengan membuat AVPlayerViewController dengan kode yang disediakan dari jawaban di atas Anda (potongan kode pertama), apa bedanya? Apa yang saya lewatkan atau harus implementasikan agar pengamat dalam metode Anda berfungsi?
Manu
6

Tujuan c

Ini hanya berfungsi di Xcode 7

Buka .hfile dan impor AVKit/AVKit.hdan AVFoundation/AVFoundation.h. Lalu buka .mfile dan tambahkan kode ini:

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];
pengguna6171720
sumber
4

Menggunakan 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()
}
}

Menggunakan 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)
}

Saya memiliki tombol putar untuk menangani ketukan tombol.

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)
        }
    }

Saya telah menambahkan pengamat yang mendengarkan 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)
    }

Ketika pemutaran video / audio selesai, atur ulang gambar tombol dan notifikasi

  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)
    }
AG
sumber
2
MPMoviePlayerController sudah usang dan kita seharusnya tidak menggunakannya lagi.
Skywalker
dapatkah Anda memberi contoh tidak menggunakan URL, untuk memeriksa menggunakan video lokal.
nyxee
4

bug (?!) di 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)
}

tidak berfungsi (kotak kosong ...)

ini bekerja:

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()
        }

URL yang sama ...

ingconti
sumber
tambahkan baris ini: player.play()setelah: self.view.layer.addSublayer(playerLayer)dan coba lagi
orazz
4

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()
    }

}
Mohammad Razipour
sumber
Di mana dalam jawaban Anda yang Anda gunakan AVPlayerViewController?
AnBisw
1

Ini bekerja untuk saya di Swift 5

Baru saja menambahkan video sampel ke proyek dari Sampel Video

Tombol Aksi yang ditambahkan untuk memutar video dari Situs Web dan Lokal dengan contoh kode cepat berikut

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()
        }
    }

}
swiftBoy
sumber
0

Cepat 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()
    })

// di sini tentu saja termasuk file model, di dalamnya saya telah memberikan url, jadi saya memanggil fungsi dari model menggunakan fungsi saja.

// juga IntroductionVideoUrl adalah URL yang saya nyatakan di dalam model.

 var introductionVideoURL: URL

Selain itu, Anda dapat menggunakan kode di bawah ini alih-alih memanggil fungsi dari model

Ganti kode ini

  let videoURL = course.introductionVideoURL

dengan

  guard let videoURL = URL(string: "https://something.mp4) else {
        return
Gulsan Borbhuiya
sumber
0
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()
})
dilip
sumber
0

Swift 5.0

Ditingkatkan dari jawaban @conti. Ini berhasil untuk saya.

 if let url = URL(string: "urUrlString"){
            let player = AVPlayer(url: url)
            let avController = AVPlayerViewController()
            avController.player = player
            // your desired frame
            avController.view.frame = self.view.frame
            self.view.addSubview(avController.view)
            self.addChild(avController)
            player.play()
        }
Ram
sumber
0

Swift 5+

Pertama-tama Anda harus mendefinisikan 2 variabel secara global di dalam pengontrol tampilan Anda.

var player: AVPlayer!
var playerViewController: AVPlayerViewController!

Di sini saya menambahkan pemain ke tampilan yang diinginkan.

@IBOutlet weak var playerView: UIView!

Kemudian tambahkan kode berikut ke metode viewDidLoad .

let videoURL = URL(string: "videoUrl")
self.player = AVPlayer(url: videoURL!)
self.playerViewController = AVPlayerViewController()
playerViewController.player = self.player
playerViewController.view.frame = self.playerView.frame
playerViewController.player?.pause()
self.playerView.addSubview(playerViewController.view)

Jika Anda tidak mendefinisikan pemain dan playerViewController secara global, Anda tidak akan dapat menyematkan pemain.

Wimukthi Rajapaksha
sumber