3

Is there any way in iOS to keep playing a sound file at a constant sound volume? So no matter if the user did set the ringtone of his phone to very low volume, I still want to play my audio file at the same volume as if the phone was set to loud. Kind of like what Siri does. She's also independent of every other sound-volume setting.

Thanks

Georg
  • 3,664
  • 3
  • 34
  • 75
  • Possible duplicate of [iOS 9: How to change volume programmatically without showing system sound bar popup?](http://stackoverflow.com/questions/33168497/ios-9-how-to-change-volume-programmatically-without-showing-system-sound-bar-po) – techloverr Mar 07 '16 at 11:46
  • Everything you need is in AVAudioSession docs https://developer.apple.com/library/ios/documentation/AVFoundation/Reference/AVAudioSession_ClassReference/ – NSDmitry Mar 07 '16 at 11:46
  • @NSDmitry I already had a look there... `outputVolume`, which sounded like it would work, is read only. The `MPVolumeView` hack... is ... well... a hack... – Georg Mar 07 '16 at 14:42

1 Answers1

1

For everybody wondering. AVAudioPlayer has a property volume that can be set higher than 1. So you would figure out what the current device volume is using AVAudioSession.sharedInstance().outputVolume and then adjust the AVAudioPlayer volume to compensate the difference.

Note that the sound quality is not going to improve ;) So best thing is just to not do that ;)

Georg
  • 3,664
  • 3
  • 34
  • 75
  • That’s actually a nice idea. Do you have an equation for this? I’m trying simple `player.volume = desiredVolume / session.outputVolume` and it does some compensation, but it doesn’t seem to play at constant volume. It’s probably some exponential/logarithmic equation. – Tricertops Jul 19 '17 at 08:17
  • 1
    I found better one: `player.volume = pow(desiredVolume / session.outputVolume, 2)`. There’s no science behind this, I only verified this empirically using my ears. This achieves constant volume for any user settings. PS: Don’t forget to handle division by zero. – Tricertops Jul 19 '17 at 09:12