1

I'm trying to implement a PlaySound() method that should play a default Notification sound. It does work perfectly. Here's the code:

    public void PlaySound()
    {
        MediaPlayer mediaPlayer = new MediaPlayer();

        var notification = RingtoneManager.GetDefaultUri(RingtoneType.Notification);
        mediaPlayer.SetDataSource(Application.Context, notification);
        Ringtone r = RingtoneManager.GetRingtone(Application.Context, notification);
        mediaPlayer.SetAudioStreamType(r.StreamType);
        mediaPlayer.Prepare();
        mediaPlayer.Start();
    }

The compiler however tells me that r.StreamType is deprecated. I've looked at various locations but can't find the 'new' way to get the StreamType. Who does know?

Paul Sinnema
  • 2,534
  • 2
  • 20
  • 33

1 Answers1

3

API 21 added MediaPlayer.SetAudioAttributes to replace mediaPlayer.SetAudioStreamType, so you can do a runtime check to determine which API methods to use:

if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
{
    var attribs = new AudioAttributes.Builder().SetFlags(AudioFlags.None).SetLegacyStreamType(Stream.Ring).Build();
    mediaPlayer.SetAudioAttributes(attribs);
}
else
{
    mediaPlayer.SetAudioStreamType(r.StreamType);
}
Zverev Evgeniy
  • 3,643
  • 25
  • 42
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • would you please add some explanation about AudioFlags.None, Stream.Ring? – Tamim Attafi May 10 '19 at 02:48
  • @TamimProduction The AudioAttributes docs go through all the different flags: https://developer.android.com/reference/android/media/AudioAttributes.html – SushiHangover May 10 '19 at 02:52
  • hello, can you please help me with this question ? https://stackoverflow.com/questions/56210872/mediaplayer-stream-alarm-not-working-properly – Tamim Attafi May 22 '19 at 06:50