AirPods Pro의 작업 데이터를 csv 파일에 기록합니다.

19299 단어 iOSSwifttech
iOS 14에서 얻은 운동 데이터를 csv 파일에 저장하는 프로그램을 만들었습니다.
소스 코드의 창고는 여기에 있습니다.
CMHeadphoneMotionManager-Sampler

csv에 기록된class
import Foundation
import CoreMotion

class MotionWriter {

    var file: FileHandle?
    var sample: Int = 0

    func open(_ filePath: URL) {
        do {
            FileManager.default.createFile(atPath: filePath.path, contents: nil, attributes: nil)
            let file = try FileHandle(forWritingTo: filePath)
            var header = ""
            header += "acceleration_x,"
            header += "acceleration_y,"
            header += "acceleration_z,"
            header += "attitude_pitch,"
            header += "attitude_roll,"
            header += "attitude_yaw,"
            header += "gravity_x,"
            header += "gravity_y,"
            header += "gravity_z,"
            header += "quaternion_x,"
            header += "quaternion_y,"
            header += "quaternion_z,"
            header += "quaternion_w,"
            header += "rotation_x,"
            header += "rotation_y,"
            header += "rotation_z"
            header += "\n"
            file.write(header.data(using: .utf8)!)
            self.file = file
        } catch let error {
            print(error)
        }
    }

    func write(_ motion: CMDeviceMotion) {
        guard let file = self.file else { return }
        var text = ""
        text += "\(motion.userAcceleration.x),"
        text += "\(motion.userAcceleration.y),"
        text += "\(motion.userAcceleration.z),"
        text += "\(motion.attitude.pitch),"
        text += "\(motion.attitude.roll),"
        text += "\(motion.attitude.yaw),"
        text += "\(motion.gravity.x),"
        text += "\(motion.gravity.y),"
        text += "\(motion.gravity.z),"
        text += "\(motion.attitude.quaternion.x),"
        text += "\(motion.attitude.quaternion.y),"
        text += "\(motion.attitude.quaternion.z),"
        text += "\(motion.attitude.quaternion.w),"
        text += "\(motion.rotationRate.x),"
        text += "\(motion.rotationRate.y),"
        text += "\(motion.rotationRate.z)"
        text += "\n"
        file.write(text.data(using: .utf8)!)
        sample += 1
    }

    func close() {
        guard let file = self.file else { return }
        file.closeFile()
        print("\(sample) sample")
        self.file = nil
    }
}

다음 내용은 csv에 저장

수집된 csv는 CreatemL을 사용하여 머신러닝 등에 사용됩니다.
MotionWriter.swift의 이용 절차.

// 生成
let writer = MotionWriter()
writer.open(path)

...

// モーションイベントの書き込み
CMHeadphoneMotionManager.startDeviceMotionUpdates(to: .main) { (motion, error) in
    if let motion = motion {
	writer.write(motion)
    }
    if let error = error {
	print(error)
    }
}

...

// 終了
writer.close()

좋은 웹페이지 즐겨찾기