Swift video recording calls camera video, and save to System album example

Source: Internet
Author: User

1, Technical introduction

(1) The Avfoundation.framework framework provides a avcapturesession class. Use it to achieve the video capture function.
(2) using Avcapturevideopreviewlayer, the camera can be photographed in real-time display on the Viewcontroller.
(3) for captured video, we use Avcapturemoviefileoutput to output it to the file.

2, the following implementation of a video function

(1) Click the "Start" button to start recording the video. The default is first saved to the Documents directory, named Temp.mp4.
(2) Click the "Stop" button to stop the video recording. The recorded video is then transferred to the system Photo gallery.

3, the effect chart is as follows:


4, sample code

Import Uikit
Import Avfoundation
Import Photos

Class Viewcontroller:uiviewcontroller, Avcapturefileoutputrecordingdelegate {

Video capture session. It is the input and output of the bridge. It coordinates the intput to output data.
Let capturesession = Avcapturesession ()
Video input device
Let Videodevice = Avcapturedevice.defaultdevicewithmediatype (Avmediatypevideo)
Audio input Devices
Let Audiodevice = Avcapturedevice.defaultdevicewithmediatype (Avmediatypeaudio)
Output the captured video to a file
Let Fileoutput = Avcapturemoviefileoutput ()

Start, stop button
var Startbutton, stopbutton:uibutton!
To indicate whether it was in the video.
var isrecording = False

Override Func Viewdidload () {
Super.viewdidload ()

Add video, audio input devices
Let Videoinput = try! Avcapturedeviceinput (Device:self.videoDevice)
Self.captureSession.addInput (Videoinput)
Let Audioinput = try! Avcapturedeviceinput (Device:self.audioDevice)
Self.captureSession.addInput (Audioinput);

Add video Capture output
Self.captureSession.addOutput (Self.fileoutput)

Use Avcapturevideopreviewlayer to display real-time footage of camera shots on Viewcontroller
Let Videolayer = Avcapturevideopreviewlayer (session:self.captureSession)
Videolayer.frame = Self.view.bounds
Videolayer.videogravity = Avlayervideogravityresizeaspectfill
Self.view.layer.addSublayer (Videolayer)

Create a button
Self.setupbutton ()
Starting session Sessions
Self.captureSession.startRunning ()
}

Create a button
Func Setupbutton () {
Create Start button
Self.startbutton = UIButton (Frame:cgrectmake (0,0,120,50))
Self.startButton.backgroundColor = Uicolor.redcolor ();
Self.startButton.layer.masksToBounds = True
Self.startButton.setTitle ("Start", Forstate:.) Normal)
Self.startButton.layer.cornerRadius = 20.0
Self.startButton.layer.position = Cgpoint (X:SELF.VIEW.BOUNDS.WIDTH/2-70,
Y:SELF.VIEW.BOUNDS.HEIGHT-50)
Self.startButton.addTarget (Self, Action: #selector (Onclickstartbutton (_:)),
forControlEvents:. Touchupinside)

Create Stop button
Self.stopbutton = UIButton (Frame:cgrectmake (0,0,120,50))
Self.stopButton.backgroundColor = Uicolor.graycolor ();
Self.stopButton.layer.masksToBounds = True
Self.stopButton.setTitle ("Stop", Forstate:.) Normal)
Self.stopButton.layer.cornerRadius = 20.0

Self.stopButton.layer.position = cgpoint (X:SELF.VIEW.BOUNDS.WIDTH/2 + 70,
Y:SELF.VIEW.BOUNDS.HEIGHT-50)
Self.stopButton.addTarget (Self, Action: #selector (Onclickstopbutton (_:)),
forControlEvents:. Touchupinside)

Add a button to the view
Self.view.addSubview (Self.startbutton);
Self.view.addSubview (Self.stopbutton);
}

Start button click, Start video
Func Onclickstartbutton (Sender:uibutton) {
If!self.isrecording {
Set up the video store address (in the documents directory, named Temp.mp4)
Let paths = Nssearchpathfordirectoriesindomains (. Documentdirectory,
. Userdomainmask, True)
Let documentsdirectory = Paths[0] as String
Let filepath:string? = "\ (documentsdirectory)/temp.mp4"
Let Fileurl:nsurl = Nsurl (fileurlwithpath:filepath!)
Start video encoding output
Fileoutput.startrecordingtooutputfileurl (FileURL, recordingdelegate:self)

Record status: In the video ...
Self.isrecording = True
Start, end button color change
Self.changebuttoncolor (Self.startbutton, Color:UIColor.grayColor ())
Self.changebuttoncolor (Self.stopbutton, Color:UIColor.redColor ())
}
}

Stop button click, stop Video
Func Onclickstopbutton (Sender:uibutton) {
If self.isrecording {
Stop video encoding output
Fileoutput.stoprecording ()

Record Status: Video end
Self.isrecording = False
Start, end button color change
Self.changebuttoncolor (Self.startbutton, Color:UIColor.redColor ())
Self.changebuttoncolor (Self.stopbutton, Color:UIColor.grayColor ())
}
}

Modify the color of a button
Func Changebuttoncolor (Target:uibutton, Color:uicolor) {
Target.backgroundcolor = Color
}

The proxy method for starting the video
Func Captureoutput (captureoutput:avcapturefileoutput!,
Didstartrecordingtooutputfileaturl fileurl:nsurl!,
Fromconnections connections: [anyobject]!) {
}

Proxy method for video end
Func Captureoutput (captureoutput:avcapturefileoutput!,
Didfinishrecordingtooutputfileaturl outputfileurl:nsurl!,
Fromconnections connections: [anyobject]!, error:nserror!) {
var message:string!
Save the recorded video to the photo gallery
Phphotolibrary.sharedphotolibrary (). Performchanges ({
Phassetchangerequest.creationrequestforassetfromvideoatfileurl (Outputfileurl)
}, Completionhandler: {(Issuccess:bool, error:nserror?) in
If issuccess {
Message = "Save success!"
} else{
Message = Save failed: \ (error!. Localizeddescription) "
}

Dispatch_async (Dispatch_get_main_queue (), {
Pop-up Cue box
Let Alertcontroller = Uialertcontroller (Title:message,
Message:nil, Preferredstyle:. Alert)
Let cancelaction = uialertaction (title: "OK", style:. Cancel, Handler:nil)
Alertcontroller.addaction (cancelaction)
Self.presentviewcontroller (Alertcontroller, Animated:true, Completion:nil)
})
})
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.