DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Building a Simple Todo App With Model Context Protocol (MCP)
  • Mastering React App Configuration With Webpack
  • How to Build a React Native Chat App for Android
  • How to Build Slack App for Audit Requests

Trending

  • Web Crawling for RAG With Crawl4AI
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  • Introduction to Retrieval Augmented Generation (RAG)

How to Implement Video Recording Using Multi-Camera in Your iOS App (Part 2)

Let users access both front and back cameras simultaneously!

By 
Amit Makhija user avatar
Amit Makhija
·
Nov. 01, 19 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
12.4K Views

Join the DZone community and get the full member experience.

Join For Free

camera-in-christmas-tree

In the first part of this tutorial, we have seen how to configure multi-camera for recording a video.

As we know that in the previous iOS version, Apple did not permit to record videos using the front and back cameras at the same time. This time, with the release of iOS 13, they have introduced this feature that allows users to capture video recording using the back and front camera.

So, let's see how it works.


What you will learn in this part of the tutorial:

  • How to implement multi-camera recording using Replaykit
You may also like: Learn Swift With This Hands-On Tutorial.

With the launch of iOS 13 and some new features, Apple has also provided AVCapture (Sample Output Delegate) to fetch front and back video, but here, we will be using ReplayKit Framework and a function called screenRecorder.

Let’s perform the task of video recording to generate output video here.

Step 1: Import Replaykit framework as follows:

import ReplayKit


Step 2: Create one shared object of RPScreenRecorder, to start and stop screen recording.

let screenRecorder = RPScreenRecorder.shared()


Step 3: We will track recording status using the isRecording variable.

var isRecording = false


Step 4: When the user taps on the screen once, it starts screen recording, and when the user double taps on screen it stops screen recording and saves output video to the user's photo library.

We have used one custom class for appending video and audio output to one video output using AssetWriter.swift.

import UIKit
import Foundation
import AVFoundation
import ReplayKit
import Photos

extension UIApplication {
    classfuncgetTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return getTopViewController(base: nav.visibleViewController)

        } else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
            return getTopViewController(base: selected)

        } else if let presented = base?.presentedViewController {
            return getTopViewController(base: presented)
        }

        return base
    }
}

class AssetWriter {
    privatevarassetWriter: AVAssetWriter?
    privatevarvideoInput: AVAssetWriterInput?
    privatevaraudioInput: AVAssetWriterInput?
    privateletfileName: String

    letwriteQueue = DispatchQueue(label: "writeQueue")

    init(fileName: String) {
        self.fileName = fileName
    }

    privatevar videoDirectoryPath: String {
        let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]

        return dir +"/Videos"
    }

    privatevarfilePath: String {
        return videoDirectoryPath +"/\(fileName)"
    }

    privatefuncsetupWriter(buffer: CMSampleBuffer) {
        if FileManager.default.fileExists(atPath: videoDirectoryPath) {
            do {
                tryFileManager.default.removeItem(atPath: videoDirectoryPath)

            } catch {
                print("fail to removeItem")
            }
        }

        do {
            tryFileManager.default.createDirectory(atPath: videoDirectoryPath, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print("fail to createDirectory")
        }

        self.assetWriter = try? AVAssetWriter(outputURL: URL(fileURLWithPath: filePath), fileType: AVFileType.mov)

        let writerOutputSettings = [
            AVVideoCodecKey: AVVideoCodecType.h264,
            AVVideoWidthKey: UIScreen.main.bounds.width,
            AVVideoHeightKey: UIScreen.main.bounds.height,

] as [String : Any]

        self.videoInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: writerOutputSettings)
        self.videoInput?.expectsMediaDataInRealTime = true

        guardlet format = CMSampleBufferGetFormatDescription(buffer),
            let stream = CMAudioFormatDescriptionGetStreamBasicDescription(format) else {
                print("fail to setup audioInput")

                return
        }

        let audioOutputSettings = [
            AVFormatIDKey : kAudioFormatMPEG4AAC,
            AVNumberOfChannelsKey : stream.pointee.mChannelsPerFrame,
            AVSampleRateKey : stream.pointee.mSampleRate,
            AVEncoderBitRateKey : 64000

            ] as [String : Any]

        self.audioInput = AVAssetWriterInput(mediaType: AVMediaType.audio, outputSettings: audioOutputSettings)
        self.audioInput?.expectsMediaDataInRealTime = true

        if let videoInput = self.videoInput, (self.assetWriter?.canAdd(videoInput))! {
            self.assetWriter?.add(videoInput)
        }

        if let audioInput = self.audioInput, (self.assetWriter?.canAdd(audioInput))! {
            self.assetWriter?.add(audioInput)
        }
    }

    publicfuncwrite(buffer: CMSampleBuffer, bufferType: RPSampleBufferType) {
        writeQueue.sync {
            ifassetWriter==nil {
                if bufferType == .audioApp {

                    setupWriter(buffer: buffer)
                }
            }

            ifassetWriter==nil {

                return
            }

            if self.assetWriter?.status== .unknown {
                print("Start writing")

                let startTime = CMSampleBufferGetPresentationTimeStamp(buffer)

                self.assetWriter?.startWriting()
                self.assetWriter?.startSession(atSourceTime: startTime)
            }

            if self.assetWriter?.status== .failed {
                print("assetWriter status: failed error: \(String(describing: self.assetWriter?.error))")

                return
            }

            if CMSampleBufferDataIsReady(buffer) == true {
                if bufferType == .video {
                    if let videoInput = self.videoInput, videoInput.isReadyForMoreMediaData {

                        videoInput.append(buffer)
                    }
                } else if bufferType == .audioApp {
                    if let audioInput = self.audioInput, audioInput.isReadyForMoreMediaData {
                        audioInput.append(buffer)

                    }
                }
            }
        }
    }

    public func finishWriting() {
        writeQueue.sync {
            self.assetWriter?.finishWriting(completionHandler: {

                print("finishWriting")

                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: self.filePath))
                }) { saved, error in
                    if saved {
                        let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
                        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)

                        alertController.addAction(defaultAction)

                        if let topVC = UIApplication.getTopViewController() {
                            topVC.present(alertController, animated: true, completion: nil)
                        }
                    }
                }
            })
        }
    }
}


Step 5: Now, we can go to the final stage of our demo.

When the user taps on screen we need to start the screen recording.

Create Start Capture function as following:

func startCapture() {
       screenRecorder.startCapture(handler: { (buffer, bufferType, err) in
            self.isRecording = true
            self.assetWriter!.write(buffer: buffer, bufferType: bufferType)
        }, completionHandler: {
            if let error = $0 {
                print(error)
            }
        })
    }


The screen recorder method will return a buffer and buffer type, which we need to pass to the assetwriter. AssetWriter will write this buffer into the URL, which we need to pass to the assetwriter initially.

Step 6: We have created object of AssetWriter assetWrite and initialized as follows:

let outputFileName = NSUUID().uuidString+".mp4"
assetWriter = AssetWriter(fileName: outputFileName)


Step 7: Now, when the user double-taps on the screen, screen recording stops. So we will use stopCapture of screen recorder method as following:

 func stopCapture() {
        screenRecorder.stopCapture {
            self.isRecording = false
            if let err = $0 {
                print(err)
            }

            self.assetWriter?.finishWriting()
        }
    }


Step 8: As we are not writing any buffer into the assetWriter, we need to tell assetWriter to finish writing and generate output video URL.

Now, AssetWriter will finish writing, and it will ask the user for permission to store video in the user photo library; if the user approves permission, it will be saved there.

AssetWriter has a finishWritng function for this.

public func finishWriting() {
        writeQueue.sync {
            self.assetWriter?.finishWriting(completionHandler: {
                print("finishWriting")

                PHPhotoLibrary.shared().performChanges({
                    PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: self.filePath))
                }) { saved, error in
                    if saved {
                        let alertController = UIAlertController(title: "Your video was successfully saved", message: nil, preferredStyle: .alert)
                        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)

                        alertController.addAction(defaultAction)

                        if let topVC = UIApplication.getTopViewController() {
                            topVC.present(alertController, animated: true, completion: nil)
                        }
                    }
                }
            })
        }
    }


Note: Some developers might get confused that RPscreenRecorder also provides startRecording and stopRecording , but we have used startCapture and stopCapture.

Why is it so?

Here’s an image to answer it

capture vs record functions in Swift


startRecording will start recording the app display. When we use the startRecording method to end recording, we need to call the stopRecroding method of RPscreenRecorder.

When we are running an AVSession and want to record screens, we need to use the startCapture method.

startCapture will start screen and audio capture. The recording initiated with startCapture must end with stopCapture.


Summing Up

We hope that you found the iPhone dual camera recording tutorial useful and your concepts about this feature are clear. You can find the source code of this dual-camera recording tutorial on Github.

Further Reading

  • Swift for the Java Guy Part 2: The Basics.
app

Opinions expressed by DZone contributors are their own.

Related

  • Building a Simple Todo App With Model Context Protocol (MCP)
  • Mastering React App Configuration With Webpack
  • How to Build a React Native Chat App for Android
  • How to Build Slack App for Audit Requests

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!