所有这些代码功能都是视图控制器上的一个按钮。该按钮应播放视频。现在代码中没有错误消息。所有这一切都是按下按钮而没有任何反应。没有错误消息。我只有一个视图控制器页面。代码如下所示。
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var moviePlayer: AVPlayerViewController?
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func playVideo(_ sender: UIButton) {
playLocalVideo()
}
func playLocalVideo(){
if moviePlayer != nil {
do {
let filePath = Bundle.main.path(forResource: "t", ofType: "mp4")
let videoURL = NSURL(fileURLWithPath: filePath!)
let player = AVPlayer(url: videoURL as URL)
let playViewController = AVPlayerViewController()
playViewController.player = player
self.present(playViewController, animated: true) {() -> Void in playViewController.player!.play()
}
} catch {
print(error)
}}}}
答案 0 :(得分:0)
在playLocalVideo中,moviePlayer: AVPlayerViewController?
未初始化,它将 nil ,因此按下按钮时没有任何反应。
class ViewController: UIViewController {
let moviePlayer = AVPlayerViewController()
...
...
func playLocalVideo(){
if let filePath = Bundle.main.path(forResource: "t", ofType: "mp4") {
let url = URL(fileURLWithPath: filePath)
let player = AVPlayer(url: url)
moviePlayer.player = player
present(moviePlayer, animated: true, completion: nil)
}
}
}
答案 1 :(得分:0)
尝试以下代码
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
let moviePlayer = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
playLocalVideo()
}
func playLocalVideo(){
if let filePath = Bundle.main.path(forResource: "t", ofType: "mp4"){
let videoURL = NSURL(fileURLWithPath: filePath)
let player = AVPlayer(url: videoURL as URL)
moviePlayer.player = player
self.present(moviePlayer, animated: true) {
self.moviePlayer.player!.play()
}
}
else{
print("Oops, something wrong when playing video.mp4")
}
}
}
确保在向目标添加视频时,它不应该是下面的图像
它应该像下面的那样