Reputation: 123
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
var playerviewcontroller = AVPlayerViewController()
var playerview = AVPlayer ()
@IBAction func playMusic(sender: AnyObject) {
let fileURL = NSURL(fileURLWithPath:"/Users/MorganEvans/Documents/Apps/32134.mp4")
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
When I use the app it does not work because the file is on my mac. Please Can someone explain how I put the video file in the project. Thanks
Upvotes: 1
Views: 497
Reputation: 3508
Try checking for the nil. Also get the video file URL from NSBundle
if let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4") {
let fileURL = NSURL(fileURLWithPath: path!)
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
Upvotes: 0
Reputation: 49730
You just need to drag and drop the file like video or image that you want to use in your project statically. Following i just add :
@IBAction func playMusic(sender: AnyObject) {
let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4")
let fileURL = NSURL(fileURLWithPath: path)
playerview = AVPlayer(URL: fileURL)
playerviewcontroller.player = playerview
self.presentViewController(playerviewcontroller, animated: true){
self.playerviewcontroller.player?.play()
}
}
Another way is Past your video, audio or image file in your project folder like following:
after that Add this file in to your xcode project by following step:
You get drapDown window and select your file as following:
And you the same code for getting file path:
let path = NSBundle.mainBundle().pathForResource("32134", ofType:"mp4")
let fileURL = NSURL(fileURLWithPath: path)
Upvotes: 1