有人能帮我吗?我正试图在同一个视图控制器中添加单独的按钮来播放单独的视频,但我不知道如何。
这是我的代码,我该怎么做?
导入UIKit导入AVKit
类ViewController: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中同时播放两个视频,您需要在Storyboard中创建两个单独的视图和两个相应的按钮。剩余功能将进入您的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.
}
}
请参阅此实现的屏幕
我使用了这段代码,它在中运行得很好
导入UIKit导入AVKit
类ViewController: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()
})
}
}
}