In today’s blog we will know how we can play a video in swift
This is the easiest way to play video in swift,
You can play a video from url or you can play a video from your project
Let’s code to play a video in your project
Step: 1
You need to create an Xcode project
Step: 2
Create a button to play video in the main.storyboard
Step: 3
Add a video in your project or you can play video from url
Step: 4
Lets’s move to view controller
Add AVFoundation fremwork in you controller
let’s know more about AVFoundation
AVFoundation is the full featured framework for working with time-based audiovisual media on iOS, macOS, watchOS and tvOS. Using AVFoundation, you can easily play, create, and edit QuickTime movies and MPEG-4 files, play HLS streams, and build powerful media functionality into your apps.
1 |
import AVFoundation |
Step: 5
We need to add the property of the AVFoundation
1 |
var playerAV: AVPlayer! |
Step: 6
Create a function and add the video player in the your view controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
func playvideo(videourl: String) { guard let firstVideo = Bundle.main.path(forResource: "video", ofType:"mp4") else { debugPrint("Video not found") return } if videourl == nil{ playerAV = AVPlayer(url: URL(fileURLWithPath: firstVideo)) }else{ let videoURL = URL(string: videourl) playerAV = AVPlayer(url: videoURL!) } let playerLayerAV = AVPlayerLayer(player: playerAV) playerLayerAV.frame = self.view.bounds self.view.layer.addSublayer(playerLayerAV) playerLayerAV.videoGravity = .resizeAspectFill playerAV.play() // you can fatch when video ended NotificationCenter.default.addObserver(self, selector: #selector(animationDidFinish(_:)), name: .AVPlayerItemDidPlayToEndTime, object: playerAV.currentItem) } |
Step: 7
Call the above function from the button
1 2 3 |
@IBAction func playvideo(sender: AnyObject) { self.playvideo(videourl: "Your video link") } |
Step: 8
You can do what you want to do after video ended.
1 2 3 4 5 6 |
@objc func animationDidFinish(_ notification: NSNotification) { playerAV.seek(to: .zero) playerAV.play() playerAV.pause() print(#function) } |
Now you can run the above code and you can now play video in your project
Thanks for reading 🙂
Hope this blog helped you with a better understanding of how to use AVAudioPlayer.
For more blogs please visit here.
For more information regarding the AVFoundation please click here.