Picking and playing videos in Swift

Tram Ho

In this article, we will learn how to record or select a video file using a video picker controller and AVPlayer class, written entirely in Swift 5.

Let’s pick some videos!

First of all you will need to add some information to your Info.plist file, because you want to access some personal data. You need to know: privacy is very important.

Since we are not going to record silent video we also have to add Privacy – Microphone Usage Description.

Our VideoPicker class will be 90% the same as the ImagePicker class. You can create an abstract class, whatever, I’ll show you the final code, then we can talk about the difference.

Those are just a few minor changes. The first is the mediaTypes attribute, you can use the “public.movie” value this time. Also, you should set videoQuality attribute on pickerController, because 4k is always better than 320.

Delegates are the last thing to change a bit. After finishing selecting the job you can get .mediaURL, which is a URL to get the multimedia file (also called the captured / selected video file). If a new file is recorded you can also save it to media library, that’s just two extra lines of code.

Playing video files using AVPlayer & UIView

This is a demo repo you can have a more intuitive look at The.Swift.Dev tutorials repository .

External sources

Conclusion

Thank you for your interest in this article, which has been translated according to the article of the same name by Tibor Bödecs.

Share the news now

Source : Viblo