【问题标题】:unable to play video when app rebuild swift应用程序快速重建时无法播放视频
【发布时间】:2021-03-23 19:52:53
【问题描述】:

使用 AVCaptureSession 重建应用程序时视频不播放(文件路径 url 保存到 coreData)

重建前后文件路径不变。

file:///private/var/mobile/Containers/Data/Application/3DA93FBC-9A20-40B4-A017-B3D5C7768301/tmp/63F6CEED-3202-4F5F-999B-5F138D73635D.mp4

我做了所有的方法,没有任何工作

这里是我录制视频的代码

  func setupPreview() {
        // Configure previewLayer
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
       previewLayer?.frame = shapeLayer.bounds
    previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    shapeLayer.layer.addSublayer(previewLayer!)
    }
func setupSession() -> Bool {
   
       captureSession.sessionPreset = AVCaptureSession.Preset.high
   
       // Setup Camera
       let camera = AVCaptureDevice.default(for: AVMediaType.video)!
   
       do {
       
           let input = try AVCaptureDeviceInput(device: camera)
       
           if captureSession.canAddInput(input) {
               captureSession.addInput(input)
               activeInput = input
           }
       } catch {
           print("Error setting device video input: \(error)")
           return false
       }
   
       // Setup Microphone
       let microphone = AVCaptureDevice.default(for: AVMediaType.audio)!
   
       do {
           let micInput = try AVCaptureDeviceInput(device: microphone)
           if captureSession.canAddInput(micInput) {
               captureSession.addInput(micInput)
           }
       } catch {
           print("Error setting device audio input: \(error)")
           return false
       }
   
   
       // Movie output
       if captureSession.canAddOutput(movieOutput) {
           captureSession.addOutput(movieOutput)
       }
   
       return true
   }

func startSession() {
   
       if !captureSession.isRunning {
        videoQueue().async {
               self.captureSession.startRunning()
        }
       }
   }
func stopSession() {
        if captureSession.isRunning {
            videoQueue().async {
                self.captureSession.stopRunning()
            }
        }
    }
func videoQueue() -> DispatchQueue {
        return DispatchQueue.main
    }
func currentVideoOrientation() -> AVCaptureVideoOrientation {
        var orientation: AVCaptureVideoOrientation
    
        switch UIDevice.current.orientation {
            case .portrait:
                orientation = AVCaptureVideoOrientation.portrait
            case .landscapeRight:
                orientation = AVCaptureVideoOrientation.landscapeLeft
            case .portraitUpsideDown:
                orientation = AVCaptureVideoOrientation.portraitUpsideDown
            default:
                 orientation = AVCaptureVideoOrientation.landscapeRight
         }
    
         return orientation
     }
func startRecording() {
 
     if movieOutput.isRecording == false {
        save.setTitle("stop", for: UIControl.State.normal)
        
         let connection = movieOutput.connection(with: AVMediaType.video)
     
         if (connection?.isVideoOrientationSupported)! {
             connection?.videoOrientation = currentVideoOrientation()
         }
     
         if (connection?.isVideoStabilizationSupported)! {
             connection?.preferredVideoStabilizationMode = AVCaptureVideoStabilizationMode.auto
         }
     
         let device = activeInput.device
     
         if (device.isSmoothAutoFocusSupported) {
         
             do {
                 try device.lockForConfiguration()
                 device.isSmoothAutoFocusEnabled = false
                 device.unlockForConfiguration()
             } catch {
                print("Error setting configuration: \(error)")
             }
         
         }
     
         //EDIT2: And I forgot this
         outputURL = tempURL()
         movieOutput.startRecording(to: outputURL, recordingDelegate: self)
     
         }
         else {
            
             stopRecording()
         }
 
    }

func tempURL() -> URL? {
  
    let directory = NSTemporaryDirectory() as NSString
 let path = directory.appendingPathComponent(NSUUID().uuidString + ".mp4")
    path22 = path
    
    let directoryURL: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let folderPath: URL = directoryURL.appendingPathComponent("Downloads", isDirectory: true)
    let fileURL: URL = folderPath.appendingPathComponent(path)
        return URL(fileURLWithPath: path)
 
}

func stopRecording() {

    if movieOutput.isRecording == true {
        movieOutput.stopRecording()
        
     }
}

这里保存到coredata中

    let managedObject = self.managedObjectContext
  entity = NSEntityDescription.entity(forEntityName: "MediaData", in: managedObject!)
      let personMO = NSManagedObject(entity: entity, insertInto: managedObject)
     
       personMO.setValue("\(self.videoURL!)", forKey: "videosS")
      personMO.setValue(dataImage, forKey: "thumbnails")
      print(personMO)
      do
      {
       try managedObject?.save()
          print("video saved")
      }
      catch
      {
          print("Catch Erroe : Failed To 
   

}

让 appdel = UIApplication.shared.delegate 为!应用委托 appdel.avplayer = AVPlayer(url: videoURL!) 打印(视频网址!) 让 playerLayer = AVPlayerLayer(玩家: appdel.avplayer) playerLayer.frame = self.view.bounds self.view.layer.addSublayer(playerLayer) appdel.avplayer?.play()

【问题讨论】:

    标签: swift avplayer avcapturesession


    【解决方案1】:

    您必须从不将完整的文件路径保存到 CoreData 或其他任何地方。文件路径不是持久的。您的应用是沙盒。沙盒路径可以随时更改,尤其是在启动和安装之间。

    相反,保存文件name 并在每次需要时reconstruct 路径。正如您最初调用FileManager.default.urls(for: .documentDirectory...) 来构造文件路径一样,您必须在每次想要访问此文件时调用它。

    【讨论】:

    • 是的,和你说的一样,当我每次文件名更改时调用下面的函数..但即使视频没有播放
    • func playVideo() { let directory = NSTemporaryDirectory() as NSString let path = directory.appendingPathComponent(NSUUID().uuidString + ".mp4") let directoryURL: URL = FileManager.default.urls( for: .documentDirectory, in: .userDomainMask)[0] let folderPath: URL = directoryURL.appendingPathComponent("Downloads", isDirectory: true) ,let fileURL: URL = folderPath.appendingPathComponent(path) print("url的文件路径是 ", URL(fileURLWithPath: path)) avplayer = AVPlayer(url:URL(fileURLWithPath: path))
    • 让 playerLayer = AVPlayerLayer(player: avplayer) playerLayer.frame = self.view.bounds, self.view.layer.addSublayer(playerLayer) avplayer.play() }
    • 好吧,你不会直接从临时文件夹中播放视频。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多