简体   繁体   English

如何在 Swift 中使用 AVPlayerViewController (AVKit) 播放视频

[英]How to play video with AVPlayerViewController (AVKit) in Swift

How do you play a video with AV Kit Player View Controller in Swift?如何在 Swift 中使用 AV Kit Player View Controller 播放视频?

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

Swift 3.x - 5.x斯威夫特 3.x - 5.x

Necessary: import AVKit , import AVFoundation必需:导入 AVKit导入 AVFoundation

AVFoundation framework is needed even if you use AVPlayer即使使用 AVPlayer 也需要 AVFoundation 框架

If you want to use AVPlayerViewController :如果你想使用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()
}

or just AVPlayer :或只是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()

It's better to put this code into the method: override func viewDidAppear(_ animated: Bool) or somewhere after.最好将此代码放入方法中: override func viewDidAppear(_animated: Bool)或之后的某处。


Objective-C目标-C

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

or just AVPlayer :或只是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];

Try this, definitely works for Swift 2.0试试这个,绝对适用于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()  

Try This尝试这个

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

Swift 3.0 Full source code: 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)
                }


            }
    }

Objective c目标c

This only works in Xcode 7这仅适用于Xcode 7

Go to .h file and import AVKit/AVKit.h and AVFoundation/AVFoundation.h .转到.h文件并导入AVKit/AVKit.hAVFoundation/AVFoundation.h Then go .m file and add this code:然后转到.m文件并添加以下代码:

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

Swift 5+斯威夫特 5+

First of all you have to define 2 variables globally inside your view controller.首先,您必须在视图控制器中全局定义 2 个变量。

var player: AVPlayer!
var playerViewController: AVPlayerViewController!

Here I'm adding player to a desired view.在这里,我将播放器添加到所需的视图中。

@IBOutlet weak var playerView: UIView!

Then add following code to the viewDidLoad method.然后将以下代码添加到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)

If you are not defining player and playerViewController globally, you won't be able to embed player.如果您没有全局定义playerplayerViewController ,您将无法嵌入播放器。

Using MPMoviePlayerController :使用 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()
}
}

Using AVPlayer :使用 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)
}

I have a play button to handle button tap.我有一个播放按钮来处理按钮点击。

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

I have added an observer listening for AVPlayerItemDidPlayToEndTimeNotification.我添加了一个监听 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)
    }

When video/audio play is finished, reset button image and notification视频/音频播放完成后,重置按钮图像和通知

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

a bug(?!) in iOS10/Swift3/Xcode 8? 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)
}

does not work (empty rect...)不起作用(空矩形...)

this works:这有效:

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

Same URL...同一个网址...

Swift 3:斯威夫特 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()
    }

}

This worked for me in Swift 5这在Swift 5 中对我有用

Just added sample video to the project from Sample Videos刚刚从Sample Videos向项目添加了示例视频

Added action Buttons for playing videos from Website and Local with the following swift code example使用以下 swift 代码示例添加了用于播放来自网站和本地的视频的操作按钮

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

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

Custom VideoPlayer using ASVideoPlayer Library from github link : https://github.com/Asbat/ASVideoPlayer使用来自 github 链接的 ASVideoPlayer 库自定义 VideoPlayer: https : //github.com/Asbat/ASVideoPlayer

// --------------------------------------------------------
// MARK:- variables
// --------------------------------------------------------

var videoPlayer = ASVideoPlayerController()
var videoData : [VideoModel] = []
var allVideoData : [AllVideoModel] = []
var cellHeights = [IndexPath: CGFloat]()
let loadingCellTableViewCellCellIdentifier = "LoadingCellTableViewCell"
var pauseIndexPath : Int = 0
var pageNumber = 1
var index = 0
var id = ""
var titleVideo = ""
var isUpdate = false
var myVideo : [MyVideo] = []
var imgs = [UIImage]()
var activityViewController : UIActivityViewController!

private var activityIndicator = NVActivityIndicatorView(frame: CGRect(x: 5, y: 5, width: 5, height: 5), type: .circleStrokeSpin, color: .systemBlue, padding: 5)
private let refreshControl = UIRefreshControl()


// --------------------------------------------------------
// MARK:- Outlets
// --------------------------------------------------------
@IBOutlet private var tableVideo: UITableView!
@IBOutlet private var _btnBack: UIButton!
@IBOutlet var _btnide: UIButton!

// ---------------------------------------------------------
// MARK:- Lifecycle
// ---------------------------------------------------------

override func viewDidLoad() {
    super.viewDidLoad()
    
    self._btnide.isHidden = true
    tableVideo.rowHeight = UITableView.automaticDimension
    tableVideo.separatorStyle = .none
    tableVideo.delegate = self
    tableVideo.dataSource = self
    tableVideo.register(UINib(nibName: "VideoPlayerTableCell", bundle: nil), forCellReuseIdentifier: "VideoPlayerTableCell")
    let cellNib = UINib(nibName:loadingCellTableViewCellCellIdentifier, bundle: nil)
    tableVideo.register(cellNib, forCellReuseIdentifier: loadingCellTableViewCellCellIdentifier)
    navigationController?.navigationBar.isHidden = true
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    ASVideoPlayerController.sharedVideoPlayer.pausePlayeVideosFor(tableView: tableVideo)
    tableVideo.scrollToRow(at: IndexPath(row: index, section: 0), at: .none, animated: true)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    tableVideo.scrollToRow(at: IndexPath(row: pauseIndexPath, section: 0), at: .none, animated: true)
    puasVideoWhenPushVC(index: pauseIndexPath)
    NotificationCenter.default.removeObserver(self)
    if tableVideo.isHidden == true {
    }
}

@IBAction func _onTapBackBtnAction(_ sender: UIButton) {
    tableVideo.scrollToRow(at: IndexPath(row: pauseIndexPath, section: 0), at: .none, animated: true)
    self.puasVideoWhenPushVC(index: pauseIndexPath)
    navigationController?.popViewController(animated: true)
    navigationController?.navigationBar.isHidden = false
}

// ---------------------------------------------------------------------
// MARK:- TableView Delegate & DataSource
// ---------------------------------------------------------------------

  extension VideoPlayerVC : 
  UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if isUpdate{
        return videoData.count
    }else{
        return allVideoData.count
    }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if tableView == tableVideo {
        return view.bounds.height
    }else {
        return UITableView.automaticDimension
    }
}


func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if tableView == tableVideo {
        if let videoCell = cell as? ASAutoPlayVideoLayerContainer, let _ = videoCell.videoURL {
            ASVideoPlayerController.sharedVideoPlayer.removeLayerFor(cell: videoCell)
        }
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableVideo.dequeueReusableCell(withIdentifier: "VideoPlayerTableCell", for: indexPath) as! VideoPlayerTableCell
    if isUpdate{
        self.id = videoData[indexPath.row].id ?? ""
        cell.configureCell(videoUrl: videoData[indexPath.row].videoLink )
    }else{
        self.id = allVideoData[indexPath.row].id ?? ""
        cell.configureCell(videoUrl: allVideoData[indexPath.row].videoLink)
    }
    cell.btnPlayPause.isSelected = false
    cell.btnPlayPause.tag = indexPath.row
    cell.btnPlayPause.addTarget(self, action: #selector(didTapPlayPauseButton(_:)), for: .touchUpInside)
    cell.btnPlayPause.setImage(UIImage(named: ""), for: .normal)
    cell.btnPlayPause.setImage(UIImage(named: "btn_play_video"), for: .selected)
    
    cell.btnUseNow.tag = indexPath.row
    cell.btnUseNow.addTarget(self, action: #selector(btnUseNowTapped(sender:)), for: .touchUpInside)
    
    cell.btnShare.tag = indexPath.row
    cell.btnShare.addTarget(self, action: #selector(btnShareTapped(sender:)), for: .touchUpInside)
    
    cell.btnSave.tag = indexPath.row
    cell.btnSave.addTarget(self, action: #selector(btnSaveTapped(sender:)), for: .touchUpInside)
    
    pauseIndexPath = indexPath.row
    return cell
}

@objc func btnUseNowTapped(sender: UIButton){
    
    self._btnide.isHidden = false
    self.pausePlayeVideos()
    let editVC = EditVideoVC()
    var fileName : String = kEmptyString
    
    if self.isUpdate{
        editVC.videoString = self.videoData[sender.tag].videoLink ?? kEmptyString
        editVC.id = self.videoData[sender.tag].id ?? kEmptyString
        editVC.titleVideo = self.videoData[sender.tag].title ?? kEmptyString
        fileName = self.videoData[sender.tag].videoZip ?? kEmptyString
        
        guard !FileManager.isExist(id: self.videoData[sender.tag].id ?? kEmptyString) else{
            print("File Downloaded")
            self.puasVideoWhenPushVC(index: sender.tag)
            self.navigationController?.pushViewController(editVC, animated: true)
            return }
        
        FileManager.download(id: self.videoData[sender.tag].id ?? kEmptyString, url: fileName) { (url) in
            guard url != nil else {
                print("not download")
                return
            }
            self.puasVideoWhenPushVC(index: sender.tag)
            self.navigationController?.pushViewController(editVC, animated: true)
        }
    }
    else{
        editVC.videoString = self.allVideoData[sender.tag].videoLink ?? kEmptyString
        editVC.id = self.allVideoData[sender.tag].id ?? kEmptyString
        editVC.titleVideo = self.allVideoData[sender.tag].title ?? kEmptyString
        fileName = self.allVideoData[sender.tag].videoZip ?? kEmptyString
        
        guard !FileManager.isExist(id: self.allVideoData[sender.tag].id ?? kEmptyString) else{
            print("File Downloaded")
            self.puasVideoWhenPushVC(index: sender.tag)
            self.navigationController?.pushViewController(editVC, animated: true)
            return }
        
        FileManager.download(id: self.allVideoData[sender.tag].id ?? kEmptyString, url: fileName) { (url) in
            guard url != nil else {
                print("not download")
                return
            }
            self.puasVideoWhenPushVC(index: sender.tag)
            self.navigationController?.pushViewController(editVC, animated: true)
        }
    }
}

@objc func btnShareTapped(sender: UIButton){
    
    if self.isUpdate{
        let video = ["\(String(describing: self.videoData[sender.tag].videoLink))"]
        self.activityViewController = UIActivityViewController(activityItems: video, applicationActivities: nil)
        self.activityViewController.setValue("Video Share", forKey: "subject")
        
        self.activityViewController.popoverPresentationController?.sourceView = self.view
        self.activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToTwitter, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.assignToContact,UIActivity.ActivityType.copyToPasteboard,UIActivity.ActivityType.mail,UIActivity.ActivityType.markupAsPDF,UIActivity.ActivityType.message,UIActivity.ActivityType.postToFacebook,UIActivity.ActivityType.postToFlickr,UIActivity.ActivityType.postToTencentWeibo,UIActivity.ActivityType.postToVimeo,UIActivity.ActivityType.postToWeibo,UIActivity.ActivityType.saveToCameraRoll]
        self.present(self.activityViewController, animated: true, completion: nil)
    }
    else{
        let categoryVideo = ["\(String(describing: self.allVideoData[sender.tag].videoLink))"]
        self.activityViewController = UIActivityViewController(activityItems: categoryVideo, applicationActivities: nil)
        self.activityViewController.setValue("Video Share", forKey: "subject")
        
        self.activityViewController.popoverPresentationController?.sourceView = self.view
        self.activityViewController.excludedActivityTypes = [ UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToTwitter]
        self.present(self.activityViewController, animated: true, completion: nil)
    }
}

@objc func btnSaveTapped(sender: UIButton){
   
    if self.isUpdate{
        self.downloadVideos(video: self.videoData[sender.tag].videoLink ?? kEmptyString)
    }else{
        self.downloadVideos(video: self.allVideoData[sender.tag].videoLink ?? kEmptyString)
    }
}


private func downloadVideos(video : String){
    Alamofire.request(video).downloadProgress(closure : { (progress) in
    }).responseData{ (response) in
        ///# Create folder in documetn directory #///

        if let data = response.result.value{
            let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Videos")
            if !FileManager.default.fileExists(atPath: path) {
                try! FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
            }
            let fileURL = URL(fileURLWithPath:path).appendingPathComponent("\(self.id)/\(self.titleVideo)/output.mp4")
            print(fileURL)
            do{
                try data.write(to: fileURL, options: .atomic)
            }catch{
                print("could not download")
            }
            print(fileURL)
        }
    }
}


// ----------------------------------------------------------------------
// MARK:- Scrollview Method
// ----------------------------------------------------------------------

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if scrollView == tableVideo {
        pauseIndexPath = Int(scrollView.contentOffset.y / scrollView.frame.size.height)
        pausePlayeVideos()
    }
}

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
    if scrollView == tableVideo {
        if !decelerate {
            pausePlayeVideos()
        }
    }
}

// ----------------------------------------------------------------------
// MARK:- Function Pause & Play Button
// ----------------------------------------------------------------------

func puasVideoWhenPushVC (index : NSInteger) {
    if isUpdate{
        guard let cell = tableVideo.cellForRow(at: IndexPath(row: index, section: 0)) as? VideoPlayerTableCell else { return }
        ASVideoPlayerController.sharedVideoPlayer.pauseVideo(forLayer: cell.videoLayer, url: videoData[index].videoLink ?? "")
    }
    else{
        guard let cell = tableVideo.cellForRow(at: IndexPath(row: index, section: 0)) as? VideoPlayerTableCell else { return }
        ASVideoPlayerController.sharedVideoPlayer.pauseVideo(forLayer: cell.videoLayer, url: allVideoData[index].videoLink ?? "")
    }
}

@objc func pausePlayeVideos(){
    ASVideoPlayerController.sharedVideoPlayer.pausePlayeVideosFor(tableView: tableVideo)
}

@objc func appEnteredFromBackground() {
    ASVideoPlayerController.sharedVideoPlayer.pausePlayeVideosFor(tableView: tableVideo, appEnteredFromBackground: true)
}

@objc func didTapPlayPauseButton(_ sender: UIButton) {
    
    guard let cell = tableVideo.cellForRow(at: IndexPath(row: sender.tag, section: 0)) as? VideoPlayerTableCell else { return }
    if sender.isSelected {
        if isUpdate{
            ASVideoPlayerController.sharedVideoPlayer.playVideo(withLayer: cell.videoLayer, url: videoData[sender.tag].videoLink ?? "")
        }else{
            ASVideoPlayerController.sharedVideoPlayer.playVideo(withLayer: cell.videoLayer, url: allVideoData[sender.tag].videoLink ?? "")
        }
    } else {
        if isUpdate{
            ASVideoPlayerController.sharedVideoPlayer.pauseVideo(forLayer: cell.videoLayer, url: videoData[sender.tag].videoLink ?? "")
        }else{
            ASVideoPlayerController.sharedVideoPlayer.pauseVideo(forLayer: cell.videoLayer, url: allVideoData[sender.tag].videoLink ?? "")
        }
    }
    sender.isSelected = !sender.isSelected
}

Swift 5斯威夫特 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()
    })

// here the course includes a model file, inside it I have given the url, so I am calling the function from model using course function. // 这里的课程包含一个模型文件,在里面我已经给出了 url,所以我使用 course 函数从模型调用函数。

// also introductionVideoUrl is a URL which I declared inside model . // 也是 IntroductionVideoUrl 是我在 model 中声明的 URL。

 var introductionVideoURL: URL

Also alternatively you can use the below code instead of calling the function from model或者,您可以使用以下代码而不是从模型调用函数

Replace this code替换此代码

  let videoURL = course.introductionVideoURL

with

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

Swift 5.0斯威夫特 5.0

Improved from @ingconti answer .从@ingconti answer 改进。 This worked for me.这对我有用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM