0

My app lets the user hear sound files, and im using AVAudioPlayer to play it.
I saw in some apps a very nice behaviour where the sound speakers changes from regular speakers to the ear speakers when the user put his phone next to his ear.

I have now idea where to start here, should i detect the phone's movement and change the output speaker or is there any native implementation for this behaviour?

Eyal
  • 10,777
  • 18
  • 78
  • 130
  • Possible duplicate of [Is there any way to monitor user's movement of iphone like the "raise to speak" feature?](http://stackoverflow.com/questions/15490385/is-there-any-way-to-monitor-users-movement-of-iphone-like-the-raise-to-speak) – Chris Droukas Nov 17 '15 at 12:36

2 Answers2

0

The most straightforward path to accomplishing this is to use proximity monitoring in UIDevice. Proximity monitoring tells you whether the phone is close to the user or not.

Listen for UIDeviceOrientationDidChangeNotification and react to proximityState changes accordingly — in your case, rerouting audio.

There's a thorough answer to a similar question here. That answer includes supplementary details to combine device motion for increased accuracy.

Community
  • 1
  • 1
Chris Droukas
  • 3,196
  • 1
  • 23
  • 26
0

What you're looking for is the proximity sensor (that little piece of hardware near the iphone ear speaker), and not any motion sensing mechanism. The proximity sensor is accessible via the public API through the UIDevice's proximityState property, which simply returns a boolean value indicating whether the sensor is close to the user or not: proximityState.
Based on that value, you can then proceed to routing your audio to the ear speaker. This can be achieved using the AVAudioSession class and specifically setting the category (setCategory:error) to AVAudioSessionCategoryPlayAndRecord.