使用监听监听结束事件
import Foundation
import AVKit
import MediaPlayer
import Flutter
class FlutterAVPlayerView: NSObject, FlutterPlatformView {
private var _flutterAVPlayerViewController: AVPlayerViewController
private var urlArray: [URL] = []
init(frame: CGRect,
viewIdentifier: CLongLong,
arguments: Dictionary<String, Any>,
binaryMessenger: FlutterBinaryMessenger) {
_flutterAVPlayerViewController = AVPlayerViewController()
_flutterAVPlayerViewController.viewDidLoad()
super.init()
if let urls = arguments["urls"] {
print("^^^^^^^ ios native av player init urls: \(urls) ^^^^^^^")
setupPlayerWithURL(urls as! [String])
} else if let filePath = arguments["file"] {
print("^^^^^^^ ios native av player init file: \(filePath) ^^^^^^^")
setupPlayerWithFile(filePath as! String)
}
}
func view() -> UIView {
return _flutterAVPlayerViewController.view
}
private func setupPlayerWithURL(_ urls: [String]) {
guard urlArray.isEmpty else {
return
}
urlArray = urls.compactMap {
URL(string: $0)
}
_flutterAVPlayerViewController.player = AVPlayer(playerItem: AVPlayerItem(url: URL(string: urls.first ?? "")!))
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: nil, queue: .main) { [weak self] _ in
self?.playNextVideo()
}
playNextVideo()
}
private func setupPlayerWithFile(_ filePath: String) {
let appDelegate = UIApplication.shared.delegate as! FlutterAppDelegate
let vc = appDelegate.window.rootViewController as! FlutterViewController
let lookUpKey = vc.lookupKey(forAsset: filePath)
if let path = Bundle.main.path(forResource: lookUpKey, ofType: nil) {
let item = AVPlayerItem(url: URL(fileURLWithPath: path))
_flutterAVPlayerViewController.player = AVPlayer(playerItem: item)
}
}
deinit {
NotificationCenter.default.removeObserver(self)
_flutterAVPlayerViewController.player?.pause()
}
private func playNextVideo() {
guard let currentPlayer = _flutterAVPlayerViewController.player else {
return
}
let nextURL = urlArray.removeFirst()
print("^^^^^^^ ios native play next video url: \(nextURL.absoluteString) ^^^^^^^")
let nextItem = AVPlayerItem(url: nextURL)
currentPlayer.replaceCurrentItem(with: nextItem)
currentPlayer.play()
}
}
标签:flutterAVPlayerViewController,filePath,ios,private,player,avplayer,let,urls,自动播放
From: https://www.cnblogs.com/guanchaoguo/p/17936508.html