How to get motion sensor value from AirPodsPro.

tukutuku_tukuyo

tukuyo

Posted on December 15, 2020

How to get motion sensor value from AirPodsPro.

Introduction.

Do you use AirPods Pro's spatial audio reproduction technology called Spatial Audio?

I haven't been able to use it as much as I'd like, because I don't get to wear AirPodsPro as much as I'd like due to my remote work.

So, in order to use my unused AirPodsPro.
I will write an article on how to get the motion sensor value to play with it.

The code for this article is here.

Requirements

  • Xcode : 12.0+
  • iOS : 14.0+
  • AirPods Pro / Max(The necessary sensors are included, so it should work.)

Describe the purpose of use in Info.plist

Using CoreMotion, so add it to Info.plist.

https___qiita-image-store.s3.ap-northeast-1.amazonaws.com_0_595030_7ac4ff49-eba1-8f65-c0f7-95eadf1ddcc3

Implementation

import UIKit
import CoreMotion

class ViewController: UIViewController, CMHeadphoneMotionManagerDelegate {

    //AirPods Pro => APP :)
    let APP = CMHeadphoneMotionManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        APP.delegate = self

        guard APP.isDeviceMotionAvailable else { return }
        APP.startDeviceMotionUpdates(to: OperationQueue.current!, withHandler: {[weak self] motion, error  in
            guard let motion = motion, error == nil else { return }
            self?.printData(motion)
        })
    }

    func printData(_ data: CMDeviceMotion) {
      print(data.attitude)            
      print(data.gravity)             
      print(data.rotationRate)        
      print(data.userAcceleration)    
      print(data.magneticField)       
      print(data.heading)             
    }

}
Enter fullscreen mode Exit fullscreen mode

In the above code, we need to do some processing when the AirPods are plugged in or not plugged in.
When you run it, you will see the data retrieved in the output.

Conclusion

I've pushed the above code to GitHub.
I've also added a sample code.
You can clone it and use it if necessary.

💖 💪 🙅 🚩
tukutuku_tukuyo
tukuyo

Posted on December 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related