DEV Community

tukuyo
tukuyo

Posted on

1

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.

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay