Reputation: 85
I'm trying to make a radio app with MediaManager on Xamarin.Forms for Android and iOS. I want to include a volume slider in the app. I've implemented it like this in XAML:
<Slider x:Name="slider" Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="4" VerticalOptions="Center" ValueChanged="ChangeMediaVolume" Minimum="0" Maximum="10" Value="5" Margin="5"/>
And for the code behind I've used this method:
private void ChangeMediaVolume(object sender, ValueChangedEventArgs args)
{
int value = (int)slider.Value;
CrossMediaManager.Current.Volume.MaxVolume = 10;
CrossMediaManager.Current.Volume.CurrentVolume = value;
}
It works perfectly in the iOS emulator, but when I launch my Android emulator, it crashes and highlights the CrossMediaManager items with the message
System.NullReferenceException has been thrown. Object reference not set to an instance of an object.
I'm not quite sure how to fix it or why it works for one platform and not the other.
Upvotes: 0
Views: 1588
Reputation: 85
So I seem to have figured out the issue. When I launch the app, the player doesn’t start until the play button has been pressed. Because of this, when the app launches the crossmediamanager isn’t fully instantiated. This is why it’s returning a null. I caught the exception so that it would load, and once the player starts everything works perfectly.
Upvotes: 0
Reputation: 9274
Yes. This is a plugin issue, I got the same result, here is a workaround for android. You can use dependenceService to achieve that.
1.Create a interface.
public interface IControlVolume
{
int setControlVolume(int value);
}
2.Achieve it in android.
[assembly: Dependency(typeof(MyControlVolume))]
namespace VideoPlay.Droid
{
class MyControlVolume : IControlVolume
{
public int setControlVolume(int value)
{
var audioMgr = (AudioManager)Forms.Context.GetSystemService(Context.AudioService);
//set the volume
audioMgr.SetStreamVolume(Android.Media.Stream.Music, value,VolumeNotificationFlags.PlaySound);
//get current value
int Volume = audioMgr.GetStreamVolume(Android.Media.Stream.Music);
return Volume;
}
}
}
Here is running gif. https://i.sstatic.net/I58kU.jpg
Upvotes: 2