How to play sound with custom volume? (Xamarin.Forms Android)

aluzi liu 486 Reputation points
2022-02-24T03:45:31.167+00:00

If my android phone's volume is set to 20%, but in my app, I want to play sound with volume 100%, how to do this?
I try:
public void PlaySound(int id)
{
var mediaPlayer = MediaPlayer.Create(MainActivity.Instance.ApplicationContext, id);
float maxVolume = 100;
float currVolume = 100;
float log1 = (float)(Math.Log(maxVolume - currVolume) / Math.Log(maxVolume));
mediaPlayer.SetVolume(log1, log1);
mediaPlayer.Start();
mediaPlayer.Completion += (sender, e) =>
{
//mediaPlayer.Reset();
mediaPlayer.Release();
};
}

But the sound still playing with system volume setting...

Developer technologies .NET Xamarin
{count} votes

1 answer

Sort by: Most helpful
  1. JarvanZhang 23,971 Reputation points
    2022-02-25T06:46:22.953+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    The MediaPlayer API is recommended for balancing the output of audio streams within an application. If you want to change the user settings of volume, please use AudioManager.setStreamVolume(int, int, int) method instead.

    Here is the related doc, you could refer to it:
    https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float,%20float)

    Best Regards,

    Jarvan Zhang


    If the response is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.