1

We can convert CMSampleBuffer to NSData with following function. But we could not find a way to convert it to Data.

We tried using

   Data(bytes: <#T##UnsafeRawPointer#>, count: <#T##Int#>)

instead of

   NSData(bytes: <#T##UnsafeRawPointer?#>, length: <#T##Int#>)

but no luck. Is there anyone who could do it.

func frameData() -> NSData {

        let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)

        CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))

        let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!)
        let height = CVPixelBufferGetHeight(imageBuffer!)
        let src_buff = CVPixelBufferGetBaseAddress(imageBuffer!)
        let nsdata = NSData(bytes: src_buff, length: bytesPerRow * height)

        CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))


        return nsdata

    }
Hope
  • 2,096
  • 3
  • 23
  • 40
  • Have you tried to convert NSData to Data as like this https://stackoverflow.com/a/49074149/3420996? – Natarajan Nov 07 '18 at 08:20
  • Just seconds ago I tried this let data = Data(bytes: src_buff!, count: bytesPerRow * height) and seems to be working. (!) – Hope Nov 07 '18 at 08:22

1 Answers1

1

Just used

       let data = Data(bytes: src_buff!, count: bytesPerRow * height)

instead of

     let nsdata = NSData(bytes: src_buff, length: bytesPerRow * height)  

The key is here was ! after src_buff for Data. Because xCode was showing some errors which is not related ! usage I could not understand ! was needed.

Hope
  • 2,096
  • 3
  • 23
  • 40