简体   繁体   English

Xamarin.Forms 的 MediaManager 音量控制

[英]MediaManager volume control for Xamarin.Forms

I'm trying to make a radio app with MediaManager on Xamarin.Forms for Android and iOS.我正在尝试在 Xamarin.Forms for Android 和 iOS 上使用 MediaManager 制作无线电应用程序。 I want to include a volume slider in the app.我想在应用程序中包含一个音量滑块。 I've implemented it like this in XAML:我已经在 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它在 iOS 模拟器中完美运行,但是当我启动我的 Android 模拟器时,它崩溃并突出显示带有消息的 CrossMediaManager 项目

System.NullReferenceException has been thrown.已抛出 System.NullReferenceException。 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.我不太确定如何修复它或为什么它适用于一个平台而不是另一个平台。

Yes.是的。 This is a plugin issue, I got the same result, here is a workaround for android.这是一个插件问题,我得到了相同的结果,这是 android 的解决方法。 You can use dependenceService to achieve that.您可以使用dependencyService 来实现这一点。

1.Create a interface. 1.创建接口。

public interface IControlVolume
{
    int setControlVolume(int value);
}

2.Achieve it in android. 2.在安卓中实现。

[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.这是运行gif。 https://imgur.com/a/odE79sc https://imgur.com/a/odE79sc

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.因此,当应用程序启动时,crossmediamanager 并未完全实例化。 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.我捕获了异常以便加载,一旦播放器启动,一切正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM