如何在SpriteKit SKScene类中启动ReplayKit屏幕录制

时间:2016-09-30 14:30:42

标签: ios swift uiviewcontroller sprite-kit replaykit

我已在ReplayKit游戏中实施SpriteKit,但由于所有内容都在GameViewController内完成,因此记录按钮显示得太早。请参阅下面的GameViewController课程:

class GameViewController: UIViewController, RPPreviewViewControllerDelegate {

var videoRecButton: UIButton!
var videoRecImage: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()

    let skView = self.view as? SKView

    if skView?.scene == nil  {
        skView?.showsFPS = true
        skView?.showsNodeCount = true
        skView?.showsPhysics = true
        skView?.ignoresSiblingOrder = false

        //starting the game with the Poster Scene
        let posterScene = PosterScene(size: skView!.bounds.size)
        posterScene.scaleMode = .aspectFill
        skView?.presentScene(posterScene)
    }

    videoRecButton = UIButton(type: .custom)
    videoRecImage = UIImage(named:"videoRecButton.png")

    videoRecButton.frame = CGRect(x:0, y: 0, width: (videoRecImage?.size.width)!, height: (videoRecImage?.size.height)!)
    videoRecButton.setImage(videoRecImage, for: .normal)
    videoRecButton.addTarget(self, action:#selector(self.videoRecButtonClicked), for: .touchUpInside)
    self.view.addSubview(videoRecButton)
}

func videoRecButtonClicked() {
    print("Button Clicked")
    startRecording()
}

func startRecording() {
    let recorder = RPScreenRecorder.shared()

    recorder.startRecording{ [unowned self] (error) in
        if let unwrappedError = error {
            print(unwrappedError.localizedDescription)
        } else {

            self.videoRecButton.addTarget(self, action:#selector(self.stopRecording), for: .touchUpInside)
        }
    }
}

func stopRecording() {
    let recorder = RPScreenRecorder.shared()

    recorder.stopRecording { [unowned self] (preview, error) in
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Start", style: .plain, target: self, action: #selector(self.startRecording))

        if let unwrappedPreview = preview {
            unwrappedPreview.previewControllerDelegate = self
            self.present(unwrappedPreview, animated: true)
        }
    }
}

func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
    dismiss(animated: true)
}

override var shouldAutorotate: Bool {
    return true
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if UIDevice.current.userInterfaceIdiom == .phone {
        return .allButUpsideDown
    } else {
        return .all
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Release any cached data, images, etc that aren't in use.
}

override var prefersStatusBarHidden: Bool {
    return true
}
}
  1. 如何从继承自startRecordingstopRecording类的类中调用SKSceneGameScene函数?

  2. 如何在videoRecButton课程中启用,停用和隐藏GameScene按钮?

  3. 更新

    根据来自crashoverride777的答案,我在SKScene课程中放置了以下代码,但屏幕记录了导航控制器之前几秒钟,并显示录制视频的预览。录制的视频只是一个黑屏,取消和保存按钮没有响应。

        func startRecording() {
        let recorder = RPScreenRecorder.shared()
    
        if #available(iOS 10.0, *) {
            recorder.startRecording{ [unowned self] (error) in
                if let unwrappedError = error {
                    print(unwrappedError.localizedDescription)
                } else {
    
                    self.stopRecording()
    
                }
            }
        } else {
            // Fallback on earlier versions
        }
    }
    
    func stopRecording() {
        let recorder = RPScreenRecorder.shared()
    
        recorder.stopRecording { [unowned self] (preview, error) in
            self.view?.window?.rootViewController?.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Start", style: .plain, target: self, action: #selector(self.startRecording))
    
            if let unwrappedPreview = preview {
                unwrappedPreview.previewControllerDelegate = self
                self.view?.window?.rootViewController?.present(unwrappedPreview, animated: true)
            }
        }
    
    }
    
    func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
        view?.window?.rootViewController?.dismiss(animated: true)
    }
    

    我创建了一个记录按钮:

    let videoRecButtonSprite = SKSpriteNode(imageNamed: "videoButton")
    videoRecButtonSprite.position = CGPoint(x: self.frame.width/15, y: self.frame.height - self.frame.height/12)
    self.addChild(videoRecButtonSprite)
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    
        for touch: AnyObject in touches {
            let location = touch.location(in: self)
            if videoRecButtonSprite.contains(location){
                startRecording()
            }
        }
    }
    

2 个答案:

答案 0 :(得分:5)

您不应在GameViewController中创建按钮,直接在SKScene中创建它。在SpriteKit游戏中使用GameViewController for UI并不是一个好习惯。

有很多关于如何在SpriteKit中创建按钮的教程。

关于ReplayKit,您可以直接在所需的SKScene中使用它,只需获取您已经拥有的代码并将其移动到相关场景。

要在SKScene中显示预览视图控制器,您可以这样说

 class ScreenRecoder: NSObject {

      /// Shared instance
      static let shared = ScreenRecorder()

      /// Preview controller
      var previewController: RPPreviewViewController?

      /// Private singleton init
      private override init() { }
 }

我还注意到您在停止录制后正在呈现View控制器。你确定要这样做吗?通常,游戏菜单中有一个单独的按钮,您可以在其中观看录制内容。

这是一般代码。我还建议你查看苹果示例游戏DemoBots。

我个人使用Singleton类来管理录制,这样就更容易管理所有方法,因为你需要它来处理不同的场景。要为类crate启动一个新的swift文件并添加此代码。

func start() {
    let sharedRecorder = RPScreenRecorder.shared()

    // Do nothing if screen recording is not available
    guard sharedRecorder.isAvailable else { return }

    // Stop previous recording if necessary
    if sharedRecorder.isRecording {
        stopScreenRecording()
    }

    print("Starting screen recording")

    // Register as the recorder's delegate to handle errors.
    sharedRecorder.delegate = self

    // Start recording
    if #available(iOS 10.0, *) {
        #if os(iOS)
            sharedRecorder.isMicrophoneEnabled = true
            //sharedRecorder.isCameraEnabled = true // fixme
        #endif

        sharedRecorder.startRecording { [unowned self] error in
            if let error = error as? NSError, error.code != RPRecordingErrorCode.userDeclined.rawValue {
                print(error.localizedDescription)
                // Show alert
                return
            }
        }
    } else {
        // Fallback on earlier versions
        sharedRecorder.startRecording(withMicrophoneEnabled: true) { error in
            if let error = error as? NSError, error.code != RPRecordingErrorCode.userDeclined.rawValue {
                print(error.localizedDescription)
                // Show alert
                return
            }
        }
    }
}

比开始录制将此方法添加到ScreenRecorder类。

 func stop() {
    let sharedRecorder = RPScreenRecorder.shared()

    // Do nothing if screen recording is not available
    guard sharedRecorder.isAvailable else { return }

    // Stop recording
    sharedRecorder.stopRecording { [unowned self] (previewViewController, error) in
        if let error = error {
            // If an error has occurred, display an alert to the user.
            print(error.localizedDescription)
            // Show alert
            return
        }

        print("Stop screen recording")

        if let previewViewController = previewViewController {
            // Set delegate to handle view controller dismissal.
            previewViewController.previewControllerDelegate = self

            /*
             Keep a reference to the `previewViewController` to
             present when the user presses on preview button.
             */
            self.previewViewController = previewViewController
        }
    }
}

要停止录音,请拨打此电话。您注意到我实际上还没有显示预览,我只是将其存储以供以后使用。这是你通常的做法。

 /// RPPreviewViewControllerDelegate
 extension ScreenRecorder: RPPreviewViewControllerDelegate {

     /// Preview controller did finish
    func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
          previewController.dismiss(animated: true, completion: nil)
    }
}

在ScreenRecorder类中创建符合ReplayKit委托的2个扩展名。

预览控制器代表

extension ScreenRecorder: RPScreenRecorderDelegate {

      /// Screen recoder did stop with error
      func screenRecorder(_ screenRecorder: RPScreenRecorder, didStopRecordingWithError error: Error, previewViewController: RPPreviewViewController?) {

         // Display the error the user to alert them that the recording failed.
        let error = error as NSError
        if error.code != RPRecordingErrorCode.userDeclined.rawValue {
            print(message: error.localizedDescription)
            // show alert
        }

         // Hold onto a reference of the `previewViewController` if not nil.
         if let previewViewController = previewViewController {
             self.previewViewController = previewViewController     
         }
      }

      /// Screen recoder did change availability
      func screenRecorderDidChangeAvailability(_ screenRecorder: RPScreenRecorder) {
           // e.g update your button UI etc
           // you can use something like delegation to pass something to your SKScenes
     }
}

和录制代表

func showPreview() {
    guard let previewViewController = previewViewController else { return }

    print("Showing screen recording preview")

    // `RPPreviewViewController` only supports full screen modal presentation.
    previewViewController.modalPresentationStyle = .fullScreen

    let rootViewController = UIApplication.shared.keyWindow?.rootViewController
    rootViewController?.present(previewViewController, animated: true, completion:nil)
}

最后创建一个方法来呈现预览。最好通过游戏菜单中的按钮来调用此功能。

ScreenRecorder.shared.start()
ScreenRecorder.shared.stop()
ScreenRecorder.shared.showPreview() // call stop before calling this

现在,您可以在项目中的任何位置调用方法

 Uri address = new Uri(@"file:///C:\");
 Console.WriteLine(address.AbsolutePath);
 Console.ReadKey();

这段代码非常直接来自DemoBots。

我认为处理屏幕录制的最好方法是在主菜单中创建一个自动录制按钮。使用UserDefaults保存它的开/关状态。如果打开它,则在游戏开始时调用startRecording,并在游戏结束时调用停止录制。比您在游戏菜单中显示预览按钮,以便在用户想要的情况下观看录制。

希望这有帮助

答案 1 :(得分:0)

DemoBots很难。记得导入ReplayKit,RPPreviewViewControllerDelegate,RPScreenRecorderDelegate。你可以在GitHub上发布你的最终代码吗,crashoverride777。这是我写的,我无法获得预览显示:

func startRecording() {
    let sharedRecorder = RPScreenRecorder.shared()

    // Do nothing if screen recording is not available
    guard sharedRecorder.isAvailable else { return }

    // Stop previous recording if necessary
    if sharedRecorder.isRecording {
        stopScreenRecording()
    }

    print("Starting screen recording")

    // Register as the recorder's delegate to handle errors.
    sharedRecorder.delegate = self

    // Start recording
    sharedRecorder.isMicrophoneEnabled = true
    //sharedRecorder.isCameraEnabled = true // fixme


    sharedRecorder.startRecording { error in
        if let error = error as NSError?, error.code != RPRecordingErrorCode.userDeclined.rawValue {
            print(error.localizedDescription)
            // Show alert
            return
        }
    }
}

func stopScreenRecording() {
    let sharedRecorder = RPScreenRecorder.shared()

    // Do nothing if screen recording is not available
    guard sharedRecorder.isAvailable else { return }

    // Stop recording
    sharedRecorder.stopRecording { [unowned self] (previewViewController, error) in
        if let error = error {
            // If an error has occurred, display an alert to the user.
            print(error.localizedDescription)
            // Show alert
            return
        }

        print("Stop screen recording")

        if let previewViewController = previewViewController {
            // Set delegate to handle view controller dismissal.
            previewViewController.previewControllerDelegate = self

            /*
             Keep a reference to the `previewViewController` to
             present when the user presses on preview button.
             */
            self.previewController = previewViewController
        }
    }
}

func previewControllerDidFinish(_ previewController: RPPreviewViewController) {
    view?.window?.rootViewController?.dismiss(animated: true)
}