Wyler: screen recording made easy on iOS

Record your app screen with sound and microphone in just two steps

Written in 2020. Some tools and APIs mentioned here have changed since.

In my previous post I talked about Warhol, an iOS library that makes easy the process of detecting a face and drawing on top within your app. As an alluring improvement, it would be awesome to be able to record the Camera Face Detection with the drawing on top.

Wyler logo: a film clapperboard in a circle above a Wyler banner

One way to achieve that would be using AVFoundation, recording a video and using later a composition to add the desired layering.

In spite of the freedom and flexibility that it provides, the complexity of the video and effects synchronization made me look further. After all, I just want to record the screen with the provided drawing, without having to add it again.

That is when ReplayKit came to my rescue. According to the docs:

Using the ReplayKit framework, users can record video from the screen, and audio from the app and microphone. They can then share their recordings with other users through email, messages, and social media. You can build app extensions for live broadcasting your content to sharing services. ReplayKit is incompatible with AVPlayer content.

It was my day of luck, it does exactly what i want! And even luckier; since the iOS 11 SDK, with the introduction of the startCapture function, we are able to compose the video and save it to disk. That way we can access it for any purpose, such as sending it to my server, streaming, editing … Before that, with the first version of ReplayKit introduced on iOS 10 SDK, we just could save the video to the Photo Library without having the chance to operate with it.

Nonetheless, it was too good to be true: the video generation is not straightforward. As mentioned before, it just provides samples periodically, delegating the responsibility of generating the video to us. This functionality can be hence encapsulated in a class, so the client app just tells when the video should start and stop recording.

That is precisely the goal of Wyler: to deal with the cumbersome ReplayKit and AVFoundation interface, wrapping it up in a clean straightforward class with two functions and a bunch of settings. This can be useful for many cases, like gaming, where the player could record its game with its commentary and share the video afterwards.

Following my habit of naming libraries starting with the letter “W”, and paying homage to one of my favourite film directors, Wyler was born.

One of the best movies ever
One of the best movies ever

Behind the Scenes

As commented before, there are few steps we must achieve in order to generate the video of our screen recording. Let’s get down to business and enumerate them.

  • Create the Asset Writer. This object will write the media data to a new file of a specified audiovisual container type. Here we specify the URL we will access later to recover the video:
private func createVideoWriter(in outputURL: URL? = nil, error: (Error) -> Void) {
    let newVideoOutputURL: URL

    if let passedVideoOutput = outputURL {
      self.videoOutputURL = passedVideoOutput
      newVideoOutputURL = passedVideoOutput
    } else {
      let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
      newVideoOutputURL = URL(fileURLWithPath: documentsPath.appendingPathComponent("WylerNewVideo.mp4"))
      self.videoOutputURL = newVideoOutputURL
    }

    do {
      try FileManager.default.removeItem(at: newVideoOutputURL)
    } catch {}

    do {
      try videoWriter = AVAssetWriter(outputURL: newVideoOutputURL, fileType: AVFileType.mp4)
    } catch let writerError as NSError {
      error(writerError)
      videoWriter = nil
      return
    }
  }
  • Create the Asset Writer Input for the Video. This object appends media samples to a single track of an asset writer’s output file:
private func addVideoWriterInput(size: CGSize?) {
    let passingSize: CGSize = size ?? UIScreen.main.bounds.size

    let videoSettings: [String: Any] = [AVVideoCodecKey: AVVideoCodecType.h264,
                                        AVVideoWidthKey: passingSize.width,
                                        AVVideoHeightKey: passingSize.height]

    let newVideoWriterInput = AVAssetWriterInput(mediaType: AVMediaType.video, outputSettings: videoSettings)

    self.videoWriterInput = newVideoWriterInput
    newVideoWriterInput.expectsMediaDataInRealTime = true
    videoWriter?.add(newVideoWriterInput)
  }
  • We do the same for the App and Mic Audio:
private func createAndAddAudioInput() -> AVAssetWriterInput {
    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    let audioInput = AVAssetWriterInput(mediaType: .audio, outputSettings: settings)

    audioInput.expectsMediaDataInRealTime = true
    videoWriter?.add(audioInput)
    
    return audioInput
  }
  • Once the inputs are added to the writer, we start the capture, adding the samples to the inputs depending on their type:
private func startCapture(error: @escaping (Error) -> Void) {
    recorder.startCapture(handler: { (sampleBuffer, sampleType, passedError) in
      if let passedError = passedError {
        error(passedError)
        return
      }

      switch sampleType {
      case .video:
        self.handleSampleBuffer(sampleBuffer: sampleBuffer)
      case .audioApp:
        self.add(sample: sampleBuffer, to: self.appAudioWriterInput)
      case .audioMic:
        self.add(sample: sampleBuffer, to: self.micAudioWriterInput)
      default:
        break
      }
    })
  }

  private func handleSampleBuffer(sampleBuffer: CMSampleBuffer) {
    if self.videoWriter?.status == AVAssetWriter.Status.unknown {
      self.videoWriter?.startWriting()
      self.videoWriter?.startSession(atSourceTime: CMSampleBufferGetPresentationTimeStamp(sampleBuffer))
    } else if self.videoWriter?.status == AVAssetWriter.Status.writing &&
      self.videoWriterInput?.isReadyForMoreMediaData == true {
      self.videoWriterInput?.append(sampleBuffer)
    }
  }
  
  private func add(sample: CMSampleBuffer, to writerInput: AVAssetWriterInput?) {
    if writerInput?.isReadyForMoreMediaData ?? false {
      writerInput?.append(sample)
    }
  }
  • And finally, when the capture is requested to stop, we ask the RPScreenRecorder to do it, finish everything, and save the video to the Photo Library if desired:
public func stoprecording(errorHandler: @escaping (Error) -> Void) {
    RPScreenRecorder.shared().stopCapture( handler: { error in
      if let error = error {
        errorHandler(error)
      }
    })

    self.videoWriterInput?.markAsFinished()
    self.micAudioWriterInput?.markAsFinished()
    self.appAudioWriterInput?.markAsFinished()
    self.videoWriter?.finishWriting {
      self.saveVideoToCameraRollAfterAuthorized(errorHandler: errorHandler)
    }
  }

As you can see, the process is not lengthy, but enough to wrap it up in a library so the client can forget about that.


Wyler Interface

Close-up of a red record button

The usage of Wyler is very straightforward, call it to start and stop recording.

Start Recording

Import Wyler in the file you are going to use it. Create an instance of ScreenRecorder, and call it to start recording whenever you want:

import Wyler

screenRecorder.startRecording(saveToCameraRoll: true, errorHandler: { error in
  debugPrint("Error when recording \(error)")
})

In order to access the video, you can set the URL where it should be saved. On top of that, you can also set the desired size. Pass these values as parameters:

import Wyler

screenRecorder.startRecording(to: yourInternalURL,
                              size: yourSize,
                              saveToCameraRoll: true, 
                              errorHandler: { error in
                                debugPrint("Error when recording \(error)")
                              })

Stop Recording

When you want to stop recording, you just have to call the recorder with stop recording:

import Wyler

screenRecorder.stoprecording(errorHandler: { error in
  debugPrint("Error when stop recording \(error)")
})

If you want to save the video to the camera, do not forget to add the Privacy — Photo Library Usage Description to the Info.plist

Everytime we start recording, the user is prompted with an alert asking for permission. It might deteriorate the user interaction experience, but at this moment this step in unavoidable. Hopefully in future releases Apple requests the authorization just once, in similar way as for the Photo Library or Microphone:

iOS alert asking permission to record the screen, with options to record screen and microphone, record screen only, or not allow

Future Improvements

There are still room for improvements for Wyler in the form of further customization. We shall give more power to those clients that require it, for instance:

  • Let the client decide whether App or Mic Audio should be recorded.
  • Make the Video and Audio Settings customizable from the outside.
  • Show the recorded status, so the client could know anytime whether it is recording or not.

Of course, I would love you for the contribution to Wyler. PRs are more than welcome with new ideas, improvements, fixes, and suggestions. This project is under MIT license and in case of issues please use the dedicated section in GitHub.

Happy Recording!

César Vargas Casaseca is a Mobile Engineer at Automattic. He writes about Swift, iOS and app architecture. More about me.

Keep reading

Leave a Reply

Your email address will not be published. Required fields are marked *