谁能帮帮我,我想在同一个视图控制器中添加单独的按钮来播放不同的视频,但我不知道怎么做。
这是我的代码,我如何做到这一点?
导入 UIKitimport AVKit
class ViewController.UIViewController { UIViewController {
@IBAction func Town(_ sender: Any) {
if let path = Bundle.main.path(forResource: "grey", ofType: "mov") {
let video = AVPlayer(url: URL(fileURLWithPath: path))
let videoPlayer = AVPlayerViewController()
videoPlayer.player = video
self.present(videoPlayer, animated: true, completion: {
video.play()
})
}
func viewDidLoad() {
super.viewDidLoad()
}
}
}
要在同一个viewController中同时播放2个视频,你需要在你的Storyboard中创建2个独立的视图和2个各自的按钮,其余的功能将在你的IBActions中实现。请使用以下代码。
class VideoPlaybackViewController: UIViewController {
@IBOutlet weak var videoView1: UIView!
@IBOutlet weak var videoView2: UIView!
@IBAction func playFirstVideo(_ sender: Any) {
guard let path = Bundle.main.path(forResource: "640", ofType: "mov") else {
print("Video Source Not Found")
return
}
playVideo(playbackURL: URL(fileURLWithPath: path), playerView: videoView1)
}
@IBAction func playSecondVideo(_ sender: Any) {
guard let path = Bundle.main.path(forResource: "720", ofType: "mov") else {
print("Video Source Not Found")
return
}
playVideo(playbackURL: URL(fileURLWithPath: path), playerView: videoView2)
}
func playVideo(playbackURL: URL, playerView: UIView) {
let player = AVPlayer(url: playbackURL)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = playerView.bounds
playerView.layer.addSublayer(playerLayer)
player.play()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
我使用了这段代码,效果非常好
导入 UIKitimport AVKit
class ViewController.UIViewController { UIViewController {
@IBOutlet weak var videoView1: UIButton!
@IBOutlet weak var videoView2: UIButton!
@IBAction func playFirstVideo(_ sender: Any) {
if let path = Bundle.main.path(forResource: "grey", ofType: "mov") {
let video = AVPlayer(url: URL(fileURLWithPath: path))
let videoPlayer = AVPlayerViewController()
videoPlayer.player = video
self.present(videoPlayer, animated: true, completion: {
video.play()
})
}
}
@IBAction func playSecondVideo(_ sender: Any) {
if let path = Bundle.main.path(forResource: "go", ofType: "mov") {
let video = AVPlayer(url: URL(fileURLWithPath: path))
let videoPlayer = AVPlayerViewController()
videoPlayer.player = video
self.present(videoPlayer, animated: true, completion: {
video.play()
})
}
}
}