ARKit:不在视图中时停止AVPlayer音频

问题描述 投票:0回答:1

我正在开发一个ARKit图像跟踪应用程序,该应用程序将AVPlayer视频叠加在图像目标(Swift5和XCode 13)上。我目前将其设置为仅同时跟踪1张图像,但是我的AR参考组中有多个包含独特视频的图像目标。

除一个问题外,一切正常,即使AR摄像机不再跟踪和渲染视频,每个视频的音频仍继续播放。如果用户导航到应用程序中的其他View Controller,则音频甚至会继续播放。

当不再跟踪其图像目标时,如何停止AVPlayer音频?

有很多代码,我不确定帮助解决该问题的必要条件(最初不包括所有内容,请让我知道其他信息是否有用。

使用AVPlayer作为材质设置平面

func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {

    let node = SCNNode()


    if let imageAnchor = anchor as? ARImageAnchor {

        let size = imageAnchor.referenceImage.physicalSize


        let videoUrl = Bundle.main.url(forResource: "Nine", withExtension: "mp4")!
        let videoPlayer = AVPlayer(url: videoUrl)
        videoPlayer.play()
        let plane = SCNPlane(width: size.width, height: size.height)
        plane.firstMaterial?.diffuse.contents = videoPlayer
        let planeNode = SCNNode(geometry: plane)
        planeNode.eulerAngles.x = -.pi / 2
    }

    node.addChildNode(planeNode)
}

return node

谢谢您的帮助!

swift xcode scenekit avplayer arkit
1个回答
0
投票
  1. 存储videoPlayer

    var videoPlayer: AVPlayer?    
    
    func renderer(_ renderer: SCNSceneRenderer, nodeFor anchor: ARAnchor) -> SCNNode? {
      let node = SCNNode()
      if let imageAnchor = anchor as? ARImageAnchor {
      ...
      let videoUrl = Bundle.main.url(forResource: "Nine", withExtension: "mp4")!
      let videoPlayer = AVPlayer(url: videoUrl)
      videoPlayer.play()
      self.videoPlayer = videoPlayer 
      ...
      }
    }
    
  2. 检查当前帧是否有图像锚点,如果没有,则暂停视频。

    func session(_ session: ARSession, didUpdate frame: ARFrame) {
      if frame.anchors.filter({$0 is ARImageAnchor}).count == 0 {
        videoPlayer?.pause()
      }
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.