0

How to get and set the volume in iOS xamarin.forms?

I have written a dependacy service in android which sets and gets the volume of the music stream on android.

I want to have a slider with the current volume set by default and allower user to set the volume by sliding the slider. Also I would like to get the maximum allowed volume level for setting the maximum limit of the slider.

Here is how I have done in android, and is working perfectly on andriod device:

public int MaxVolume()
{
    AudioManager audioMan = (AudioManager)global::Android.App.Application.Context.GetSystemService(Context.AudioService);
    return audioMan.GetStreamMaxVolume(Android.Media.Stream.Music);
}

public void SetVolume(int volume)
{
    AudioManager audioMan = (AudioManager)global::Android.App.Application.Context.GetSystemService(Context.AudioService);
    audioMan.SetStreamVolume(Android.Media.Stream.Music, volume, 0);
}

public int GetCurrentVolume()
{
    AudioManager audioMan = (AudioManager)global::Android.App.Application.Context.GetSystemService(Context.AudioService);
    return audioMan.GetStreamVolume(Android.Media.Stream.Music);
}

How do I achieve same on iOS? I tried float volume = AVAudioSession.SharedInstance().OutputVolume;, but doesn't give me volume.

Arti
  • 2,993
  • 11
  • 68
  • 121

2 Answers2

0

To Specify volume u need to use AVPlayer

 AVAudioSession.SharedInstance().SetCategory(AVAudioSessionCategory.Playback , AVAudioSessionCategoryOptions.MixWithOthers);

 var player = new AVPlayer(audioFilePath);
 player.Volume = 0.2f;  
 player.Play();

Where sound level goes from 0.0f to 1f

More about AVPlayer

If you need to rise or low it just add the value. Also you can have a look at MPVolumeView This is a slider that changes volume programmatically

Danil Kurkin
  • 283
  • 2
  • 11
0

I solved it like this (get the current output volume only):

AVAudioSession.SharedInstance().SetActive(true);
return AVAudioSession.SharedInstance().OutputVolume;

The first instruction is required to get updated values, the second returns a float between 0 and 1 indicating the current output volume.

Thanks to these references:

output volume: Get System Volume iOS

update the value: How to get System Volume iOS?

IvanF.
  • 513
  • 10
  • 18